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/analyzers/correctness/no_string_case_mismatch.rs | crates/rome_js_analyze/src/analyzers/correctness/no_string_case_mismatch.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::*;
use rome_rowan::{declare_node_union, AstNode, AstSeparatedList, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Disallow comparison of expressions modifying the string case with non-compliant value.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// if (s.toUpperCase() === "Abc") {}
/// ```
///
/// ```js,expect_diagnostic
/// while (s.toLowerCase() === "Abc") {}
/// ```
/// ### Valid
///
/// ```js
/// if (s.toUpperCase() === "ABC") {}
/// while (s.toLowerCase() === "abc") {}
/// for (;s.toLocaleLowerCase() === "ABC";) {}
/// while (s.toLocaleUpperCase() === "abc") {}
/// for (let s = "abc"; s === "abc"; s = s.toUpperCase()) {}
/// ```
pub(crate) NoStringCaseMismatch {
version: "11.0.0",
name: "noStringCaseMismatch",
recommended: true,
}
}
impl Rule for NoStringCaseMismatch {
type Query = Ast<QueryCandidate>;
type State = CaseMismatchInfo;
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Vec<Self::State> {
let query = ctx.query();
match query {
QueryCandidate::JsBinaryExpression(expr) => CaseMismatchInfo::from_binary_expr(expr)
.into_iter()
.collect(),
QueryCandidate::JsSwitchStatement(stmt) => CaseMismatchInfo::from_switch_stmt(stmt),
}
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let query = ctx.query();
let mut diagnostic = match query {
QueryCandidate::JsBinaryExpression(expr) => RuleDiagnostic::new(
rule_category!(),
expr.range(),
markup! { "This expression always returns false." },
),
QueryCandidate::JsSwitchStatement(..) => RuleDiagnostic::new(
rule_category!(),
state.literal.range(),
markup! { "This case will never match." },
),
};
diagnostic = diagnostic
.description("This expression always returns false, because the string is converted and will never match")
.detail(
state.call.range(),
markup! {
"This call convert the string to " { state.expected_case.description() }
},
)
.detail(
state.literal.range(),
markup! {
"... but this value is not in " { state.expected_case.description() }
},
);
Some(diagnostic)
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
mutation.replace_node(
state.literal.clone(),
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsStringLiteralExpression(
make::js_string_literal_expression(make::js_string_literal(
&state.expected_value,
)),
),
),
);
Some(JsRuleAction {
mutation,
message: markup! {"Use "<Emphasis>{state.expected_case.description()}</Emphasis>" string value."}.to_owned(),
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
})
}
}
declare_node_union! {
pub(crate) QueryCandidate = JsBinaryExpression | JsSwitchStatement
}
pub(crate) struct CaseMismatchInfo {
expected_case: ExpectedStringCase,
expected_value: String,
call: JsCallExpression,
literal: AnyJsExpression,
}
impl CaseMismatchInfo {
fn from_binary_expr(expr: &JsBinaryExpression) -> Option<Self> {
let (left, right) = match expr.as_fields() {
JsBinaryExpressionFields {
left: Ok(left),
right: Ok(right),
operator_token: Ok(op),
} if matches!(op.kind(), JsSyntaxKind::EQ2 | JsSyntaxKind::EQ3) => (left, right),
_ => return None,
};
let (call, literal) = match (left, right) {
(AnyJsExpression::JsCallExpression(call), other)
| (other, AnyJsExpression::JsCallExpression(call)) => (call, other),
_ => return None,
};
Self::compare_call_with_literal(call, literal)
}
fn from_switch_stmt(stmt: &JsSwitchStatement) -> Vec<Self> {
match stmt.as_fields() {
JsSwitchStatementFields {
discriminant: Ok(AnyJsExpression::JsCallExpression(call)),
cases,
..
} => cases
.into_iter()
.flat_map(|case| case.as_js_case_clause().and_then(|case| case.test().ok()))
.flat_map(|test| Self::compare_call_with_literal(call.clone(), test))
.collect(),
_ => Vec::new(),
}
}
fn compare_call_with_literal(call: JsCallExpression, literal: AnyJsExpression) -> Option<Self> {
let expected_case = ExpectedStringCase::from_call(&call)?;
let static_value = literal.as_static_value()?;
let literal_value = static_value.text();
let expected_value = expected_case.convert(literal_value);
if literal_value != expected_value {
Some(Self {
expected_case,
expected_value,
call,
literal,
})
} else {
None
}
}
}
enum ExpectedStringCase {
Upper,
Lower,
}
impl ExpectedStringCase {
fn from_call(call: &JsCallExpression) -> Option<Self> {
if call.arguments().ok()?.args().len() != 0 {
return None;
}
let callee = call.callee().ok()?;
let member_expr = AnyJsMemberExpression::cast_ref(callee.syntax())?;
let member_name = member_expr.member_name()?;
let member_name = member_name.text();
if member_name == "toLowerCase" {
return Some(Self::Lower);
}
if member_name == "toUpperCase" {
return Some(Self::Upper);
}
None
}
fn convert(&self, s: &str) -> String {
match self {
ExpectedStringCase::Upper => s.to_uppercase(),
ExpectedStringCase::Lower => s.to_lowercase(),
}
}
fn description(&self) -> &str {
match self {
ExpectedStringCase::Upper => "upper case",
ExpectedStringCase::Lower => "lower case",
}
}
}
| 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/no_invalid_constructor_super.rs | crates/rome_js_analyze/src/analyzers/correctness/no_invalid_constructor_super.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::{markup, MarkupBuf};
use rome_js_syntax::{
AnyJsClass, AnyJsExpression, JsAssignmentOperator, JsConstructorClassMember, JsLogicalOperator,
};
use rome_rowan::{AstNode, AstNodeList, TextRange};
declare_rule! {
/// Prevents the incorrect use of `super()` inside classes.
/// It also checks whether a call `super()` is missing from classes that extends other constructors.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// class A {
/// constructor() {
/// super();
/// }
/// }
/// ```
///
/// ```js,expect_diagnostic
/// class A extends undefined {
/// constructor() {
/// super();
/// }
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// export default class A extends B {
/// constructor() {
/// super();
/// }
/// }
/// ```
///
/// ```js
/// export class A {
/// constructor() {}
/// }
/// ```
///
pub(crate) NoInvalidConstructorSuper {
version: "10.0.0",
name: "noInvalidConstructorSuper",
recommended: true,
}
}
pub(crate) enum NoInvalidConstructorSuperState {
UnexpectedSuper(TextRange),
BadExtends {
extends_range: TextRange,
super_range: TextRange,
},
}
impl NoInvalidConstructorSuperState {
fn range(&self) -> &TextRange {
match self {
NoInvalidConstructorSuperState::UnexpectedSuper(range) => range,
NoInvalidConstructorSuperState::BadExtends { super_range, .. } => super_range,
}
}
fn message(&self) -> MarkupBuf {
match self {
NoInvalidConstructorSuperState::UnexpectedSuper(_) => {
(markup! { "This class should not have a "<Emphasis>"super()"</Emphasis>" call. You should remove it." }).to_owned()
}
NoInvalidConstructorSuperState::BadExtends { .. } => {
(markup! { "This class calls "<Emphasis>"super()"</Emphasis>", but the class extends from a non-constructor." }).to_owned()
}
}
}
fn detail(&self) -> Option<(&TextRange, MarkupBuf)> {
match self {
NoInvalidConstructorSuperState::BadExtends { extends_range, .. } => Some((
extends_range,
markup! { "This is where the non-constructor is used." }.to_owned(),
)),
_ => None,
}
}
}
impl Rule for NoInvalidConstructorSuper {
type Query = Ast<JsConstructorClassMember>;
type State = NoInvalidConstructorSuperState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
// we check first if `super()` is part of a constructor class member
let super_expression = node.body().ok()?.statements().iter().find_map(|statement| {
statement
.as_js_expression_statement()?
.expression()
.ok()?
.as_js_call_expression()?
.callee()
.ok()?
.as_js_super_expression()
.cloned()
});
let extends_clause = node
.syntax()
.ancestors()
.find_map(|node| AnyJsClass::cast(node)?.extends_clause());
match (super_expression, extends_clause) {
(Some(super_expression), Some(extends_clause)) => {
let super_class = extends_clause.super_class().ok()?;
if let Some(is_valid) = is_valid_constructor(super_class.clone()) {
if !is_valid {
return Some(NoInvalidConstructorSuperState::BadExtends {
super_range: super_expression.syntax().text_trimmed_range(),
extends_range: super_class.syntax().text_trimmed_range(),
});
} else {
None
}
} else {
None
}
}
(Some(super_expression), None) => Some(
NoInvalidConstructorSuperState::UnexpectedSuper(super_expression.range()),
),
_ => None,
}
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let mut diagnostic = RuleDiagnostic::new(rule_category!(), state.range(), state.message());
if let Some((range, text)) = state.detail() {
diagnostic = diagnostic.detail(range, text);
}
Some(diagnostic)
}
}
fn is_valid_constructor(expression: AnyJsExpression) -> Option<bool> {
match expression.omit_parentheses() {
AnyJsExpression::JsAwaitExpression(await_expression) => {
is_valid_constructor(await_expression.argument().ok()?)
}
AnyJsExpression::JsThisExpression(_)
| AnyJsExpression::JsFunctionExpression(_)
| AnyJsExpression::JsCallExpression(_)
| AnyJsExpression::JsImportCallExpression(_)
| AnyJsExpression::JsImportMetaExpression(_)
| AnyJsExpression::JsYieldExpression(_)
| AnyJsExpression::JsNewExpression(_)
| AnyJsExpression::JsNewTargetExpression(_)
| AnyJsExpression::JsStaticMemberExpression(_)
| AnyJsExpression::JsClassExpression(_) => Some(true),
AnyJsExpression::JsIdentifierExpression(identifier) => {
Some(!identifier.name().ok()?.is_undefined())
}
AnyJsExpression::JsAssignmentExpression(assignment) => {
let operator = assignment.operator().ok()?;
if matches!(
operator,
JsAssignmentOperator::Assign
| JsAssignmentOperator::LogicalAndAssign
| JsAssignmentOperator::LogicalOrAssign
| JsAssignmentOperator::NullishCoalescingAssign
) {
return is_valid_constructor(assignment.right().ok()?);
}
Some(false)
}
AnyJsExpression::JsLogicalExpression(expression) => {
let operator = expression.operator().ok()?;
if matches!(operator, JsLogicalOperator::LogicalAnd) {
return is_valid_constructor(expression.right().ok()?);
}
is_valid_constructor(expression.left().ok()?)
.or_else(|| is_valid_constructor(expression.right().ok()?))
}
AnyJsExpression::JsConditionalExpression(conditional_expression) => {
is_valid_constructor(conditional_expression.alternate().ok()?)
.or_else(|| is_valid_constructor(conditional_expression.consequent().ok()?))
}
AnyJsExpression::JsSequenceExpression(sequence_expression) => {
is_valid_constructor(sequence_expression.right().ok()?)
}
AnyJsExpression::JsTemplateExpression(template_expression) => {
// Tagged templates can return anything
Some(template_expression.tag().is_some())
}
AnyJsExpression::TsInstantiationExpression(instantiation_expression) => {
is_valid_constructor(instantiation_expression.expression().ok()?)
}
AnyJsExpression::TsAsExpression(type_assertion) => {
is_valid_constructor(type_assertion.expression().ok()?)
}
AnyJsExpression::TsNonNullAssertionExpression(type_assertion) => {
is_valid_constructor(type_assertion.expression().ok()?)
}
AnyJsExpression::TsSatisfiesExpression(type_assertion) => {
is_valid_constructor(type_assertion.expression().ok()?)
}
AnyJsExpression::TsTypeAssertionExpression(type_assertion) => {
is_valid_constructor(type_assertion.expression().ok()?)
}
AnyJsExpression::JsComputedMemberExpression(_)
| AnyJsExpression::AnyJsLiteralExpression(_)
| AnyJsExpression::JsArrayExpression(_)
| AnyJsExpression::JsArrowFunctionExpression(_)
| AnyJsExpression::JsBinaryExpression(_)
| AnyJsExpression::JsBogusExpression(_)
| AnyJsExpression::JsInstanceofExpression(_)
| AnyJsExpression::JsObjectExpression(_)
| AnyJsExpression::JsPostUpdateExpression(_)
| AnyJsExpression::JsPreUpdateExpression(_)
| AnyJsExpression::JsSuperExpression(_)
| AnyJsExpression::JsUnaryExpression(_)
| AnyJsExpression::JsxTagExpression(_) => Some(false),
AnyJsExpression::JsInExpression(_) => None,
// Should not be triggered because we called `omit_parentheses`
AnyJsExpression::JsParenthesizedExpression(_) => 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/correctness/no_unused_labels.rs | crates/rome_js_analyze/src/analyzers/correctness/no_unused_labels.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{
declare_rule, ActionCategory, AddVisitor, Phases, QueryMatch, Queryable, Rule, RuleDiagnostic,
ServiceBag, Visitor, VisitorContext,
};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{
JsBreakStatement, JsContinueStatement, JsLabeledStatement, JsLanguage, TextRange, WalkEvent,
};
use rome_rowan::{AstNode, BatchMutationExt, Language, NodeOrToken, SyntaxNode};
use rustc_hash::FxHashMap;
use crate::control_flow::AnyJsControlFlowRoot;
use crate::JsRuleAction;
declare_rule! {
/// Disallow unused labels.
///
/// Labels that are declared and never used are most likely an error due to incomplete refactoring.
///
/// Source: https://eslint.org/docs/latest/rules/no-unused-labels
///
/// ## Examples
///
/// ### Invalid
///
/// ```cjs,expect_diagnostic
/// LOOP: for (const x of xs) {
/// if (x > 0) {
/// break;
/// }
/// f(x);
/// }
/// ```
///
/// ### Valid
///
/// ```cjs
/// LOOP: for (const x of xs) {
/// if (x > 0) {
/// break LOOP;
/// }
/// f(x);
/// }
/// ```
///
pub(crate) NoUnusedLabels {
version: "12.0.0",
name: "noUnusedLabels",
recommended: true,
}
}
#[derive(Default)]
struct UnusedLabelVisitor {
root_id: usize,
// Key = (root_id, label)
labels: FxHashMap<(usize, String), JsLabeledStatement>,
}
impl UnusedLabelVisitor {
fn insert(&mut self, label: String, label_stmt: JsLabeledStatement) {
self.labels.insert((self.root_id, label), label_stmt);
}
fn remove(&mut self, label: String) -> Option<JsLabeledStatement> {
self.labels.remove(&(self.root_id, label))
}
}
impl Visitor for UnusedLabelVisitor {
type Language = JsLanguage;
fn visit(
&mut self,
event: &WalkEvent<SyntaxNode<Self::Language>>,
mut ctx: VisitorContext<Self::Language>,
) {
match event {
WalkEvent::Enter(node) => {
if AnyJsControlFlowRoot::cast_ref(node).is_some() {
self.root_id += 1;
} else if let Some(label_stmt) = JsLabeledStatement::cast_ref(node) {
if let Ok(label_tok) = label_stmt.label_token() {
self.insert(label_tok.text_trimmed().to_owned(), label_stmt);
}
} else if let Some(break_stmt) = JsBreakStatement::cast_ref(node) {
if let Some(label_tok) = break_stmt.label_token() {
self.remove(label_tok.text_trimmed().to_owned());
}
} else if let Some(continue_stmt) = JsContinueStatement::cast_ref(node) {
if let Some(label_tok) = continue_stmt.label_token() {
self.remove(label_tok.text_trimmed().to_owned());
}
}
}
WalkEvent::Leave(node) => {
if AnyJsControlFlowRoot::cast_ref(node).is_some() {
self.root_id -= 1;
} else if let Some(stmt_label) = JsLabeledStatement::cast_ref(node) {
if let Ok(label_tok) = stmt_label.label_token() {
let result = self.remove(label_tok.text_trimmed().to_owned());
if let Some(label_stmt) = result {
ctx.match_query(UnusedLabel(label_stmt));
}
}
}
}
}
}
}
pub(crate) struct UnusedLabel(JsLabeledStatement);
impl QueryMatch for UnusedLabel {
fn text_range(&self) -> TextRange {
self.0.range()
}
}
impl Queryable for UnusedLabel {
type Input = Self;
type Language = JsLanguage;
type Output = JsLabeledStatement;
type Services = ();
fn build_visitor(
analyzer: &mut impl AddVisitor<Self::Language>,
_: &<Self::Language as Language>::Root,
) {
analyzer.add_visitor(Phases::Syntax, UnusedLabelVisitor::default);
}
// Extract the output object from the input type
fn unwrap_match(_: &ServiceBag, query: &Self::Input) -> Self::Output {
query.0.clone()
}
}
impl Rule for NoUnusedLabels {
type Query = UnusedLabel;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(_: &RuleContext<Self>) -> Option<Self::State> {
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let unused_label = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
unused_label.label_token().ok()?.text_trimmed_range(),
markup! {
"Unused "<Emphasis>"label"</Emphasis>"."
},
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let unused_label = ctx.query();
let body = unused_label.body().ok()?;
let mut mutation = ctx.root().begin();
mutation.replace_element(
NodeOrToken::Node(unused_label.syntax().to_owned()),
NodeOrToken::Node(body.syntax().to_owned()),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! {"Remove the unused "<Emphasis>"label"</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/correctness/no_unreachable_super.rs | crates/rome_js_analyze/src/analyzers/correctness/no_unreachable_super.rs | use std::{collections::VecDeque, iter, slice};
use roaring::bitmap::RoaringBitmap;
use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_control_flow::InstructionKind;
use rome_js_syntax::{
AnyJsClass, AnyJsExpression, JsConstructorClassMember, JsSuperExpression, JsSyntaxElement,
JsThisExpression, JsThrowStatement, TextRange, WalkEvent,
};
use rome_rowan::AstNode;
use crate::control_flow::{AnyJsControlFlowRoot, BasicBlock, ControlFlowGraph};
declare_rule! {
/// Ensures the `super()` constructor is called exactly once on every code
/// path in a class constructor before `this` is accessed if the class has
/// a superclass
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// class A extends B {
/// constructor() {}
/// }
/// ```
///
/// ```js,expect_diagnostic
/// class A extends B {
/// constructor(value) {
/// this.prop = value;
/// super();
/// }
/// }
/// ```
///
/// ```js,expect_diagnostic
/// class A extends B {
/// constructor(cond) {
/// if(cond) {
/// super();
/// }
/// }
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// export default class A extends B {
/// constructor() {
/// super();
/// }
/// }
/// ```
///
/// ```js
/// export class A {
/// constructor() {}
/// }
/// ```
///
pub(crate) NoUnreachableSuper {
version: "12.0.0",
name: "noUnreachableSuper",
recommended: true,
}
}
#[allow(clippy::enum_variant_names)]
pub(crate) enum RuleState {
/// The constructor reads or write from `this` before calling `super`
ThisBeforeSuper { this: TextRange, super_: TextRange },
/// The constructor may call `super` multiple times
DuplicateSuper { first: TextRange, second: TextRange },
/// The constructor may read or write from `this` without calling `super`
ThisWithoutSuper { this: TextRange },
/// The constructor may return without calling `super`
ReturnWithoutSuper { return_: Option<TextRange> },
}
impl Rule for NoUnreachableSuper {
type Query = ControlFlowGraph;
type State = RuleState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let cfg = ctx.query();
// Ignore non-constructor functions
let constructor = JsConstructorClassMember::cast_ref(&cfg.node)?;
// Find the class this constructor belongs to
let class = constructor
.syntax()
.ancestors()
.find_map(AnyJsClass::cast)?;
// Do not run the rule if the class has no extends clause or is extending a literal expression
let extends_clause = class.extends_clause()?;
let super_class = extends_clause.super_class().ok()?;
if matches!(super_class, AnyJsExpression::AnyJsLiteralExpression(_)) {
return None;
}
// Iterate over all the blocks, performing block-local checks and
// collecting metadata on the control flow graph in various
// acceleration structures
let mut outgoing_edges = BlockMap::default();
let mut incoming_edges = BlockMap::default();
let mut this_blocks = BlockMap::default();
let mut super_blocks = BlockMap::default();
let mut return_blocks = BlockMap::default();
for (block_index, block) in cfg.blocks.iter().enumerate() {
let signal = inspect_block(
&mut outgoing_edges,
&mut incoming_edges,
&mut this_blocks,
&mut super_blocks,
&mut return_blocks,
block,
block_index.try_into().expect("integer overflow"),
);
if let Some(signal) = signal {
return Some(signal);
}
}
// Traverse the control flow graph "downwards" starting from blocks
// containing a `super()` call towards the return points of the constructor
let mut queue = VecDeque::new();
for (block_id, super_expression) in &super_blocks {
if let Some(outgoing_edges) = outgoing_edges.get(block_id) {
for next_block in outgoing_edges {
queue.push_back((next_block, block_id, super_expression));
}
}
}
// During the traversal, all the `super()` expressions that precede a
// given block are collected into the `predecessors`
let mut predecessors = BlockMap::default();
while let Some((block_id, prev_block, super_expression)) = queue.pop_front() {
let visited = predecessors
.entry(block_id)
.get_or_insert_with(BlockMap::<&JsSuperExpression>::default);
let previous_node = visited
.insert(prev_block, super_expression)
.filter(|previous_node| *previous_node == super_expression);
if previous_node.is_some() {
continue;
}
if let Some(outgoing_edges) = outgoing_edges.get(block_id) {
for next_block in outgoing_edges {
queue.push_back((next_block, block_id, super_expression));
}
}
}
// Check all the blocks containing a `super()` expression and emit an
// error if they have a predecessor (as it means `super()` may have
// already been called)
for (block_id, second) in &super_blocks {
if let Some(predecessors) = predecessors.get(block_id) {
if let Some(first) = predecessors.values().next() {
return Some(RuleState::DuplicateSuper {
first: first.syntax().text_trimmed_range(),
second: second.syntax().text_trimmed_range(),
});
}
}
}
// For each block containing a `this`, check that it has a predecessor for each of its incoming edges
for (block_id, this_expression) in &this_blocks {
if super_blocks.contains_key(block_id) {
continue;
}
if let Some(predecessors) = predecessors.get(block_id) {
if let Some(incoming_edges) = incoming_edges.get(block_id) {
if predecessors.len() != incoming_edges.len() {
return Some(RuleState::ThisWithoutSuper {
this: this_expression.syntax().text_trimmed_range(),
});
}
}
} else {
return Some(RuleState::ThisWithoutSuper {
this: this_expression.syntax().text_trimmed_range(),
});
}
}
// For each block containing a return instruction, check that it has a predecessor for each of its incoming edges
for (block_id, return_range) in &return_blocks {
if super_blocks.contains_key(block_id) {
continue;
}
if let Some(predecessors) = predecessors.get(block_id) {
if let Some(incoming_edges) = incoming_edges.get(block_id) {
if predecessors.len() != incoming_edges.len() {
return Some(RuleState::ReturnWithoutSuper {
return_: *return_range,
});
}
}
} else {
return Some(RuleState::ReturnWithoutSuper {
return_: *return_range,
});
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
match state {
RuleState::ThisBeforeSuper { this, super_ } => Some(
RuleDiagnostic::new(
rule_category!(),
ctx.query().node.text_trimmed_range(),
markup! { "This constructor has code paths accessing `"<Emphasis>"this"</Emphasis>"` before `"<Emphasis>"super()"</Emphasis>"` is called." },
)
.detail(this, markup! { "`"<Emphasis>"this"</Emphasis>"` is accessed here:" })
.detail(super_, markup! { "`"<Emphasis>"super()"</Emphasis>"` is only called here:" })
.note("If this is intentional, add an explicit throw statement in unsupported paths."),
),
RuleState::ThisWithoutSuper { this } => Some(
RuleDiagnostic::new(
rule_category!(),
ctx.query().node.text_trimmed_range(),
markup! { "This constructor has code paths accessing `"<Emphasis>"this"</Emphasis>"` without calling `"<Emphasis>"super()"</Emphasis>"` first." },
)
.detail(this, markup! { "`"<Emphasis>"this"</Emphasis>"` is accessed here:" })
.note("If this is intentional, add an explicit throw statement in unsupported paths."),
),
RuleState::DuplicateSuper { first, second } if *first == *second => Some(
RuleDiagnostic::new(
rule_category!(),
ctx.query().node.text_trimmed_range(),
markup! { "This constructor calls `"<Emphasis>"super()"</Emphasis>"` in a loop." },
)
.detail(first, markup! { "`"<Emphasis>"super()"</Emphasis>"` is called here:" }),
),
RuleState::DuplicateSuper { first, second } => Some(
RuleDiagnostic::new(
rule_category!(),
ctx.query().node.text_trimmed_range(),
markup! { "This constructor has code paths where `"<Emphasis>"super()"</Emphasis>"` is called more than once." },
)
.detail(first, markup! { "`"<Emphasis>"super()"</Emphasis>"` is first called here:" })
.detail(second, markup! { "`"<Emphasis>"super()"</Emphasis>"` is then called again here:" }),
),
RuleState::ReturnWithoutSuper { return_: Some(range) } => Some(
RuleDiagnostic::new(
rule_category!(),
ctx.query().node.text_trimmed_range(),
markup! { "This constructor has code paths that return without calling `"<Emphasis>"super()"</Emphasis>"` first." },
)
.detail(range, markup! { "This statement returns from the constructor before `"<Emphasis>"super()"</Emphasis>"` has been called:" })
.note("If this is intentional, add an explicit throw statement in unsupported paths."),
),
RuleState::ReturnWithoutSuper { return_: None } => Some(
RuleDiagnostic::new(
rule_category!(),
ctx.query().node.text_trimmed_range(),
markup! { "This constructor has code paths that return without calling `"<Emphasis>"super()"</Emphasis>"`." },
)
.note("If this is intentional, add an explicit throw statement in unsupported paths."),
),
}
}
}
/// Performs block-local control flow checks to ensure `super()` is only called once, and
/// always before all `this` expressions or return instructions within a single block
///
/// This function also collects various acceleration structures for the graph-wide analysis step:
/// - `outgoing_edges` and `incoming_edges` map the index of a block to the set of the indices of
/// all the blocks that have a jump coming from- or pointing to this block respectively
/// - `this_blocks` maps the index of a block to the first `this` expression it contains if it has any
/// - `super_blocks` maps the index of a block to the first `super()` expression it contains if it has any
/// - `return_blocks` maps the index of a block to the first return instruction it contains if it has any,
/// with an optional text range if the instruction was created from an explicit `return`
fn inspect_block(
outgoing_edges: &mut BlockMap<RoaringBitmap>,
incoming_edges: &mut BlockMap<RoaringBitmap>,
this_blocks: &mut BlockMap<JsThisExpression>,
super_blocks: &mut BlockMap<JsSuperExpression>,
return_blocks: &mut BlockMap<Option<TextRange>>,
block: &BasicBlock,
block_index: u32,
) -> Option<RuleState> {
let mut has_this = None;
let mut has_super: Option<(usize, JsSuperExpression)> = None;
let mut has_return = None;
// Iterator over all the instructions in the block
for (inst_index, inst) in block.instructions.iter().enumerate() {
// If the instruction has a corresponding node, visit its descendants
// to detect any `super()` or `this` expression
if let Some(node) = inst.node.as_ref().and_then(JsSyntaxElement::as_node) {
let mut iter = node.preorder();
while let Some(event) = iter.next() {
let node = match event {
WalkEvent::Enter(node) => {
if AnyJsControlFlowRoot::can_cast(node.kind()) {
iter.skip_subtree();
continue;
}
node
}
WalkEvent::Leave(_) => continue,
};
// If we find a `super()` node but the block already has one, exit with an error immediately
if let Some(super_node) = JsSuperExpression::cast_ref(&node) {
if let Some((prev_index, prev_super)) = &has_super {
if *prev_index < inst_index {
return Some(RuleState::DuplicateSuper {
first: prev_super.syntax().text_trimmed_range(),
second: super_node.syntax().text_trimmed_range(),
});
}
} else {
has_super = Some((inst_index, super_node));
}
}
has_this = has_this.or_else(|| {
let node = JsThisExpression::cast_ref(&node)?;
Some((inst_index, node))
});
}
}
match inst.kind {
InstructionKind::Statement => {}
// If the instruction is a jump, stores the metadata about this edge
// and stop analyzing the block if its unconditional
InstructionKind::Jump {
block, conditional, ..
} => {
outgoing_edges
.entry(block_index)
.get_or_insert_with(RoaringBitmap::default)
.insert(block.index());
incoming_edges
.entry(block.index())
.get_or_insert_with(RoaringBitmap::default)
.insert(block_index);
if !conditional {
break;
}
}
// If the instruction is a return, store its optional text range and stop analyzing the block
InstructionKind::Return => {
if let Some(node) = &inst.node {
if !JsThrowStatement::can_cast(node.kind()) {
has_return = Some(Some(node.text_trimmed_range()));
}
} else {
has_return = Some(None);
}
break;
}
}
}
// If the block has a `super()` node and at least one `this` expression,
// check that the first `this` node comes after the call to `super()`
//
// NOTE: The CFG has no representation of control flow within expressions
// at the moment, meaning the ordering of `super()` and `this` within the
// same expression statement is *NOT* checked (for instance the statement
// `this.value && super();` is allowed)
if let (Some((this_index, this_node)), Some((super_index, super_node))) =
(&has_this, &has_super)
{
if this_index < super_index {
return Some(RuleState::ThisBeforeSuper {
this: this_node.syntax().text_trimmed_range(),
super_: super_node.syntax().text_trimmed_range(),
});
}
}
if let Some((_, node)) = has_this {
this_blocks.insert(block_index, node);
}
if let Some((_, node)) = has_super {
super_blocks.insert(block_index, node);
}
if let Some(return_range) = has_return {
return_blocks.insert(block_index, return_range);
}
None
}
/// Fast implementation of `Map<u32, T>` backed by a vector
struct BlockMap<T> {
storage: Vec<Option<T>>,
}
impl<T> Default for BlockMap<T> {
fn default() -> Self {
Self {
storage: Vec::new(),
}
}
}
impl<T> BlockMap<T> {
/// Insert `value` into the map at the position `key`
///
/// If the map did not have this key present, None is returned.
///
/// If the map did have this key present, the value is updated, and the old value is returned.
fn insert(&mut self, key: u32, value: T) -> Option<T> {
let index = usize::try_from(key).expect("integer overflow");
if self.storage.len() <= index {
self.storage.resize_with(index + 1, || None);
}
self.storage[index].replace(value)
}
/// Gets the given key’s corresponding entry in the map for in-place manipulation.
fn entry(&mut self, key: u32) -> &mut Option<T> {
let index = usize::try_from(key).expect("integer overflow");
if self.storage.len() <= index {
self.storage.resize_with(index + 1, || None);
}
&mut self.storage[index]
}
/// Returns a reference to the value corresponding to the key.
fn get(&self, key: u32) -> Option<&T> {
let index = usize::try_from(key).expect("integer overflow");
self.storage.get(index)?.as_ref()
}
/// Returns true if the map contains a value for the specified key.
fn contains_key(&self, key: u32) -> bool {
self.get(key).is_some()
}
/// Returns the number of elements in the map.
fn len(&self) -> u64 {
self.values().count().try_into().expect("integer overflow")
}
/// An iterator visiting all values in the map, sorted by their key in ascending order
fn values(&self) -> impl Iterator<Item = &T> {
self.storage.iter().filter_map(Option::as_ref)
}
}
impl<'a, T> IntoIterator for &'a BlockMap<T> {
type Item = (u32, &'a T);
type IntoIter = iter::FilterMap<
iter::Enumerate<slice::Iter<'a, Option<T>>>,
fn((usize, &Option<T>)) -> Option<(u32, &T)>,
>;
fn into_iter(self) -> Self::IntoIter {
self.storage.iter().enumerate().filter_map(|(index, slot)| {
Some((index.try_into().expect("integer overflow"), slot.as_ref()?))
})
}
}
| 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/no_unsafe_finally.rs | crates/rome_js_analyze/src/analyzers/correctness/no_unsafe_finally.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::*;
use rome_rowan::{declare_node_union, AstNode};
declare_rule! {
/// Disallow control flow statements in finally blocks.
///
/// JavaScript suspends the control flow statements of `try` and `catch` blocks until
/// the execution of finally block finishes. So, when `return`, `throw`, `break` or `continue`
/// is used in finally, control flow statements inside `try` and `catch` are overwritten,
/// which is considered as unexpected behavior.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// (() => {
/// try {
/// return 1; // 1 is returned but suspended until finally block ends
/// } catch(err) {
/// return 2;
/// } finally {
/// return 3; // 3 is returned before 1, which we did not expect
/// }
/// })();
/// ```
///
/// ```js,expect_diagnostic
/// (() => {
/// try {
/// throw new Error("Try"); // error is thrown but suspended until finally block ends
/// } finally {
/// return 3; // 3 is returned before the error is thrown, which we did not expect
/// }
/// })();
/// ```
///
/// ```js,expect_diagnostic
/// (() => {
/// try {
/// throw new Error("Try")
/// } catch(err) {
/// throw err; // The error thrown from try block is caught and re-thrown
/// } finally {
/// throw new Error("Finally"); // Finally(...) is thrown, which we did not expect
/// }
/// })();
/// ```
///
/// ```js,expect_diagnostic
/// (() => {
/// label: try {
/// return 0; // 0 is returned but suspended until finally block ends
/// } finally {
/// break label; // It breaks out the try-finally block, before 0 is returned.
/// }
/// return 1;
/// })();
/// ```
///
/// ```js,expect_diagnostic
/// function a() {
/// switch (condition) {
/// case 'a': {
/// try {
/// console.log('a');
/// return;
/// } finally {
/// break;
/// }
/// }
/// case 'b': {
/// console.log('b');
/// }
/// }
/// }
///```
///
/// ### Valid
///
/// ```js
/// let foo = function() {
/// try {
/// return 1;
/// } catch(err) {
/// return 2;
/// } finally {
/// console.log("hola!");
/// }
/// };
/// ```
///
/// ```js
/// let foo = function() {
/// try {
/// return 1;
/// } catch(err) {
/// return 2;
/// } finally {
/// let a = function() {
/// return "hola!";
/// }
/// }
/// };
/// ```
///
/// ```js
/// let foo = function(a) {
/// try {
/// return 1;
/// } catch(err) {
/// return 2;
/// } finally {
/// switch(a) {
/// case 1: {
/// console.log("hola!")
/// break;
/// }
/// }
/// }
/// };
/// ```
///
pub(crate) NoUnsafeFinally {
version: "11.0.0",
name: "noUnsafeFinally",
recommended: true,
}
}
declare_node_union! {
pub(crate) ControlFlowStatement = JsReturnStatement | JsThrowStatement | JsBreakStatement | JsContinueStatement
}
impl Rule for NoUnsafeFinally {
type Query = Ast<ControlFlowStatement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let query = ctx.query();
if query.in_finally_block()? {
Some(())
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let query = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
query.syntax().text_trimmed_range(),
markup! {
"Unsafe usage of '"{ query.description() }"'."
},
).note(markup! {
"'"{ query.description() }"' in 'finally' overwrites the control flow statements inside 'try' and 'catch'."
}))
}
}
impl ControlFlowStatement {
fn in_finally_block(&self) -> Option<bool> {
let mut node = self.syntax().clone();
let mut is_label_inside_finally = false;
let label = self.label_token();
loop {
let kind = node.kind();
let should_stop = match self {
Self::JsBreakStatement(it) if it.label_token().is_none() => {
sentinel_for_break(kind)
}
Self::JsContinueStatement(_) => sentinel_for_continue(kind),
_ => sentinel_for_throw_or_return(kind),
};
if should_stop {
break;
}
if let Some(label) = &label {
if let Some(parent) = node.parent().and_then(JsLabeledStatement::cast) {
if parent
.label_token()
.ok()
.map_or(false, |it| it.text_trimmed() == label.text_trimmed())
{
is_label_inside_finally = true;
}
}
}
if node.kind() == JsSyntaxKind::JS_FINALLY_CLAUSE {
return Some(!is_label_inside_finally);
}
node = node.parent()?;
}
Some(false)
}
fn label_token(&self) -> Option<JsSyntaxToken> {
match self {
Self::JsReturnStatement(_) | Self::JsThrowStatement(_) => None,
Self::JsBreakStatement(it) => it.label_token(),
Self::JsContinueStatement(it) => it.label_token(),
}
}
fn description(&self) -> &str {
match self {
Self::JsReturnStatement(_) => "return",
Self::JsThrowStatement(_) => "throw",
Self::JsBreakStatement(_) => "break",
Self::JsContinueStatement(_) => "continue",
}
}
}
fn sentinel_for_break(kind: JsSyntaxKind) -> bool {
sentinel_for_continue(kind) || JsSwitchStatement::can_cast(kind)
}
fn sentinel_for_continue(kind: JsSyntaxKind) -> bool {
use JsSyntaxKind::*;
sentinel_for_throw_or_return(kind)
|| matches!(
kind,
JS_DO_WHILE_STATEMENT
| JS_WHILE_STATEMENT
| JS_FOR_OF_STATEMENT
| JS_FOR_IN_STATEMENT
| JS_FOR_STATEMENT
)
}
fn sentinel_for_throw_or_return(kind: JsSyntaxKind) -> bool {
AnyJsRoot::can_cast(kind)
|| AnyJsFunction::can_cast(kind)
|| AnyJsClassMember::can_cast(kind)
|| AnyJsObjectMember::can_cast(kind)
}
| 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/use_yield.rs | crates/rome_js_analyze/src/analyzers/correctness/use_yield.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{
declare_rule, AddVisitor, Phases, QueryMatch, Queryable, Rule, RuleDiagnostic, ServiceBag,
Visitor, VisitorContext,
};
use rome_console::markup;
use rome_js_syntax::{AnyFunctionLike, JsLanguage, JsYieldExpression, TextRange, WalkEvent};
use rome_rowan::{AstNode, AstNodeList, Language, SyntaxNode};
declare_rule! {
/// Require generator functions to contain `yield`.
///
/// This rule generates warnings for generator functions that do not have the `yield` keyword.
///
/// Source: [require-await](https://eslint.org/docs/latest/rules/require-yield).
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// function* foo() {
/// return 10;
/// }
/// ```
///
/// ### Valid
/// ```js
/// function* foo() {
/// yield 5;
/// return 10;
/// }
///
/// function foo() {
/// return 10;
/// }
///
/// // This rule does not warn on empty generator functions.
/// function* foo() { }
/// ```
pub(crate) UseYield {
version: "12.0.0",
name: "useYield",
recommended: true,
}
}
#[derive(Default)]
struct MissingYieldVisitor {
/// Vector to hold a function node and a boolean indicating whether the function
/// contains an `yield` expression or not.
stack: Vec<(AnyFunctionLike, bool)>,
}
impl Visitor for MissingYieldVisitor {
type Language = JsLanguage;
fn visit(
&mut self,
event: &WalkEvent<SyntaxNode<Self::Language>>,
mut ctx: VisitorContext<Self::Language>,
) {
match event {
WalkEvent::Enter(node) => {
// When the visitor enters a function node, push a new entry on the stack
if let Some(node) = AnyFunctionLike::cast_ref(node) {
self.stack.push((node, false));
}
if JsYieldExpression::can_cast(node.kind()) {
// When the visitor enters a `yield` expression, set the
// `has_yield` flag for the top entry on the stack to `true`
if let Some((_, has_yield)) = self.stack.last_mut() {
*has_yield = true;
}
}
}
WalkEvent::Leave(node) => {
// When the visitor exits a function, if it matches the node of the top-most
// entry of the stack and the `has_yield` flag is `false`, emit a query match
if let Some(exit_node) = AnyFunctionLike::cast_ref(node) {
if let Some((enter_node, has_yield)) = self.stack.pop() {
if enter_node == exit_node && !has_yield {
ctx.match_query(MissingYield(enter_node));
}
}
}
}
}
}
}
pub(crate) struct MissingYield(AnyFunctionLike);
impl QueryMatch for MissingYield {
fn text_range(&self) -> TextRange {
self.0.range()
}
}
impl Queryable for MissingYield {
type Input = Self;
type Language = JsLanguage;
type Output = AnyFunctionLike;
type Services = ();
fn build_visitor(
analyzer: &mut impl AddVisitor<Self::Language>,
_: &<Self::Language as Language>::Root,
) {
analyzer.add_visitor(Phases::Syntax, MissingYieldVisitor::default);
}
fn unwrap_match(_: &ServiceBag, query: &Self::Input) -> Self::Output {
query.0.clone()
}
}
impl Rule for UseYield {
type Query = MissingYield;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let query = ctx.query();
// Don't emit diagnostic for non-generators or generators with an empty body
if !query.is_generator() || query.statements()?.is_empty() {
return None;
}
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
markup! {"This generator function doesn't contain "<Emphasis>"yield"</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/correctness/no_setter_return.rs | crates/rome_js_analyze/src/analyzers/correctness/no_setter_return.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{JsReturnStatement, JsSetterClassMember, JsSetterObjectMember};
use rome_rowan::{declare_node_union, AstNode};
use crate::control_flow::AnyJsControlFlowRoot;
declare_rule! {
/// Disallow returning a value from a setter
///
/// While returning a value from a setter does not produce an error, the returned value is being ignored. Therefore, returning a value from a setter is either unnecessary or a possible error.
///
/// Only returning without a value is allowed, as it’s a control flow statement.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// class A {
/// set foo(x) {
/// return x;
/// }
/// }
/// ```
///
/// ```js,expect_diagnostic
/// const b = {
/// set foo(x) {
/// return x;
/// },
/// };
/// ```
///
/// ```js,expect_diagnostic
/// const c = {
/// set foo(x) {
/// if (x) {
/// return x;
/// }
/// },
/// };
/// ```
///
/// ### Valid
///
/// ```js
/// // early-return
/// class A {
/// set foo(x) {
/// if (x) {
/// return;
/// }
/// }
/// }
/// ```
///
/// ```js
/// // not a setter
/// class B {
/// set(x) {
/// return x;
/// }
/// }
/// ```
///
/// ```
pub(crate) NoSetterReturn {
version: "11.0.0",
name: "noSetterReturn",
recommended: true,
}
}
declare_node_union! {
pub(crate) JsSetterMember = JsSetterClassMember | JsSetterObjectMember
}
impl Rule for NoSetterReturn {
type Query = Ast<JsReturnStatement>;
type State = JsSetterMember;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let ret = ctx.query();
// Do not take arg-less returns into account
let _arg = ret.argument()?;
let setter = ret
.syntax()
.ancestors()
.find(|x| AnyJsControlFlowRoot::can_cast(x.kind()))
.and_then(JsSetterMember::cast);
setter
}
fn diagnostic(ctx: &RuleContext<Self>, setter: &Self::State) -> Option<RuleDiagnostic> {
let ret = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
ret.range(),
markup! {
"The setter should not "<Emphasis>"return"</Emphasis>" a value."
},
)
.detail(setter.range(), "The setter is here:")
.note("Returning a value from a setter is ignored."),
)
}
}
| 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/use_valid_for_direction.rs | crates/rome_js_analyze/src/analyzers/correctness/use_valid_for_direction.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{
AnyJsExpression, JsAssignmentOperator, JsBinaryOperator, JsForStatement,
JsIdentifierAssignment, JsIdentifierExpression, JsPostUpdateOperator, JsUnaryOperator,
TextRange,
};
declare_rule! {
/// Enforce "for" loop update clause moving the counter in the right direction.
///
/// A for loop with a stop condition that can never be reached,
/// such as one with a counter that moves in the wrong direction, will run infinitely.
/// While there are occasions when an infinite loop is intended, the convention is to construct such loops as while loops.
/// More typically, an infinite for loop is a bug.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// for (var i = 0; i < 10; i--) {
/// }
/// ```
///
/// ```js,expect_diagnostic
/// for (var i = 10; i >= 0; i++) {
/// }
/// ```
///
/// ```js,expect_diagnostic
/// for (var i = 0; i > 10; i++) {
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// for (var i = 0; i < 10; i++) {
/// }
/// ```
pub(crate) UseValidForDirection {
version: "10.0.0",
name: "useValidForDirection",
recommended: true,
}
}
pub struct RuleRangeState {
l_paren_range: TextRange,
r_paren_range: TextRange,
}
impl Rule for UseValidForDirection {
type Query = Ast<JsForStatement>;
type State = RuleRangeState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let n = ctx.query();
let l_paren_range = n.l_paren_token().ok()?.text_trimmed_range();
let r_paren_range = n.r_paren_token().ok()?.text_trimmed_range();
let rule_state = RuleRangeState {
l_paren_range,
r_paren_range,
};
let test = n.test()?;
let binary_expr = test.as_js_binary_expression()?;
let operator = binary_expr.operator().ok()?;
let is_less_than = matches!(
operator,
JsBinaryOperator::LessThan | JsBinaryOperator::LessThanOrEqual
);
let is_greater_than = matches!(
operator,
JsBinaryOperator::GreaterThan | JsBinaryOperator::GreaterThanOrEqual
);
if !is_less_than && !is_greater_than {
return None;
}
match n.update()? {
AnyJsExpression::JsPostUpdateExpression(update_expr) => {
let binary_expr_left = binary_expr.left().ok()?;
let counter_ident = binary_expr_left.as_js_identifier_expression()?;
let update_expr_operand = update_expr.operand().ok()?;
let update_ident = update_expr_operand.as_js_identifier_assignment()?;
if !is_identifier_same(counter_ident, update_ident)? {
return None;
}
if update_expr.operator().ok()? == JsPostUpdateOperator::Increment
&& is_greater_than
{
return Some(rule_state);
}
if update_expr.operator().ok()? == JsPostUpdateOperator::Decrement && is_less_than {
return Some(rule_state);
}
}
AnyJsExpression::JsAssignmentExpression(assignment_expr) => {
let binary_expr_left = binary_expr.left().ok()?;
let counter_ident = binary_expr_left.as_js_identifier_expression()?;
let assignment_expr_left = assignment_expr.left().ok()?;
let update_ident = assignment_expr_left
.as_any_js_assignment()?
.as_js_identifier_assignment()?;
if !is_identifier_same(counter_ident, update_ident)? {
return None;
}
if assignment_expr
.right()
.ok()?
.as_js_identifier_expression()
.is_some()
{
return None;
}
match assignment_expr.operator().ok()? {
JsAssignmentOperator::AddAssign => {
if is_greater_than {
return Some(rule_state);
}
let assignment_expr_right = assignment_expr.right().ok()?;
let unary_expr = assignment_expr_right.as_js_unary_expression()?;
if is_less_than && unary_expr.operator().ok()? == JsUnaryOperator::Minus {
return Some(rule_state);
}
}
JsAssignmentOperator::SubtractAssign => {
if is_less_than {
return Some(rule_state);
}
let assignment_expr_right = assignment_expr.right().ok()?;
let unary_expr = assignment_expr_right.as_js_unary_expression()?;
if is_greater_than && unary_expr.operator().ok()? == JsUnaryOperator::Minus
{
return Some(rule_state);
}
}
_ => return None,
}
}
_ => return None,
}
None
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
state.l_paren_range.cover(state.r_paren_range),
markup! {
"The update clause in this loop moves the variable in the wrong direction."
},
))
}
}
fn is_identifier_same(
counter_ident: &JsIdentifierExpression,
update_ident: &JsIdentifierAssignment,
) -> Option<bool> {
Some(
counter_ident
.name()
.ok()?
.value_token()
.ok()?
.text_trimmed()
== update_ident.name_token().ok()?.text_trimmed(),
)
}
| 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/no_constructor_return.rs | crates/rome_js_analyze/src/analyzers/correctness/no_constructor_return.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{JsConstructorClassMember, JsReturnStatement};
use rome_rowan::AstNode;
use crate::control_flow::AnyJsControlFlowRoot;
declare_rule! {
/// Disallow returning a value from a `constructor`.
///
/// Returning a value from a `constructor` of a class is a possible error.
/// Forbidding this pattern prevents errors resulting from unfamiliarity with JavaScript or a copy-paste error.
///
/// Only returning without a value is allowed, as it’s a control flow statement.
///
/// Source: https://eslint.org/docs/latest/rules/no-constructor-return
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// class A {
/// constructor() {
/// return 0;
/// }
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// class A {
/// constructor() {}
/// }
/// ```
///
/// ```js
/// class B {
/// constructor(x) {
/// return;
/// }
/// }
/// ```
///
/// ```
pub(crate) NoConstructorReturn {
version: "11.0.0",
name: "noConstructorReturn",
recommended: true,
}
}
impl Rule for NoConstructorReturn {
type Query = Ast<JsReturnStatement>;
type State = JsConstructorClassMember;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let ret = ctx.query();
// Do not take arg-less returns into account
let _arg = ret.argument()?;
let constructor = ret
.syntax()
.ancestors()
.find(|x| AnyJsControlFlowRoot::can_cast(x.kind()))
.and_then(JsConstructorClassMember::cast);
constructor
}
fn diagnostic(ctx: &RuleContext<Self>, constructor: &Self::State) -> Option<RuleDiagnostic> {
let ret = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
ret.range(),
markup! {
"The "<Emphasis>"constructor"</Emphasis>" should not "<Emphasis>"return"</Emphasis>" a value."
},
).detail(
constructor.range(),
"The constructor is here:"
).note("Returning a value from a constructor is ignored."))
}
}
| 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/no_precision_loss.rs | crates/rome_js_analyze/src/analyzers/correctness/no_precision_loss.rs | use std::num::IntErrorKind;
use std::ops::RangeInclusive;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::numbers::split_into_radix_and_number;
use rome_js_syntax::JsNumberLiteralExpression;
use rome_rowan::AstNode;
declare_rule! {
/// Disallow literal numbers that lose precision
///
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const x = 9007199254740993
/// ```
///
/// ```js,expect_diagnostic
/// const x = 5123000000000000000000000000001
/// ```
///
/// ```js,expect_diagnostic
/// const x = 1230000000000000000000000.0
/// ```
///
/// ```js,expect_diagnostic
/// const x = .1230000000000000000000000
/// ```
///
/// ```js,expect_diagnostic
/// const x = 0X20000000000001
/// ```
///
/// ```js,expect_diagnostic
/// const x = 0X2_000000000_0001;
/// ```
///
/// ### Valid
///
/// ```js
/// const x = 12345
/// const x = 123.456
/// const x = 123e34
/// const x = 12300000000000000000000000
/// const x = 0x1FFFFFFFFFFFFF
/// const x = 9007199254740991
/// const x = 9007_1992547409_91
/// ```
///
pub(crate) NoPrecisionLoss {
version: "11.0.0",
name: "noPrecisionLoss",
recommended: true,
}
}
impl Rule for NoPrecisionLoss {
type Query = Ast<JsNumberLiteralExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if is_precision_lost(node)? {
Some(())
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
let value = node.as_number()?;
Some(
RuleDiagnostic::new(
rule_category!(),
node.syntax().text_trimmed_range(),
markup! { "This number literal will lose precision at runtime." },
)
.note(markup! { "The value at runtime will be "<Emphasis>{ value.to_string() }</Emphasis> }),
)
}
}
fn is_precision_lost(node: &JsNumberLiteralExpression) -> Option<bool> {
let token = node.value_token().ok()?;
let num = token.text_trimmed();
let (radix, num) = split_into_radix_and_number(num);
if radix == 10 {
is_precision_lost_in_base_10(&num)
} else {
Some(is_precision_lost_in_base_other(&num, radix))
}
}
fn is_precision_lost_in_base_10(num: &str) -> Option<bool> {
let normalized = NormalizedNumber::new(num);
let precision = normalized.precision();
if precision == 0 {
return Some(false);
}
if precision > 100 {
return Some(true);
}
let parsed = num.parse::<f64>().ok()?;
let stored_num = format!("{:.*e}", precision - 1, parsed);
Some(stored_num != normalized.to_scientific())
}
fn is_precision_lost_in_base_other(num: &str, radix: u32) -> bool {
let parsed = match i64::from_str_radix(num, radix) {
Ok(x) => x,
Err(e) => {
return matches!(
e.kind(),
IntErrorKind::PosOverflow | IntErrorKind::NegOverflow
)
}
};
const MAX_SAFE_INTEGER: i64 = 2_i64.pow(53) - 1;
const MIN_SAFE_INTEGER: i64 = -MAX_SAFE_INTEGER;
const SAFE_RANGE: RangeInclusive<i64> = MIN_SAFE_INTEGER..=MAX_SAFE_INTEGER;
!SAFE_RANGE.contains(&parsed)
}
fn remove_leading_zeros(num: &str) -> &str {
num.trim_start_matches('0')
}
fn remove_trailing_zeros(num: &str) -> &str {
num.trim_end_matches('0')
}
#[derive(Debug)]
/// Normalized number in the form `0.{digits}.{digits_rest}e{exponent}`
struct NormalizedNumber<'a> {
digits: &'a str,
digits_rest: &'a str,
exponent: isize,
}
impl NormalizedNumber<'_> {
fn new(num: &str) -> NormalizedNumber<'_> {
let num = remove_leading_zeros(num);
let mut split = num.splitn(2, ['e', 'E']);
// SAFETY: unwrap is ok because even an empty string will produce one part.
let mantissa = split.next().unwrap();
let exponent = split.next();
let mut mantissa_parts = mantissa.splitn(2, '.');
// SAFETY: unwrap is ok because even an empty string will produce one part.
let mut normalized = match (mantissa_parts.next().unwrap(), mantissa_parts.next()) {
("", Some(fraction)) => {
let digits = remove_leading_zeros(fraction);
NormalizedNumber {
digits,
digits_rest: "",
exponent: digits.len() as isize - fraction.len() as isize,
}
}
(integer, Some(fraction)) => NormalizedNumber {
digits: integer,
digits_rest: fraction,
exponent: integer.len() as isize,
},
(integer, None) => {
let digits = remove_trailing_zeros(integer);
NormalizedNumber {
digits,
digits_rest: "",
exponent: integer.len() as isize,
}
}
};
if let Some(exponent) = exponent.and_then(|it| it.parse::<isize>().ok()) {
normalized.exponent += exponent;
}
normalized
}
fn to_scientific(&self) -> String {
let fraction = &self.digits[1..];
if fraction.is_empty() && self.digits_rest.is_empty() {
format!("{}e{}", &self.digits[..1], self.exponent - 1)
} else {
format!(
"{}.{}{}e{}",
&self.digits[..1],
fraction,
self.digits_rest,
self.exponent - 1
)
}
}
fn precision(&self) -> usize {
self.digits.len() + self.digits_rest.len()
}
}
| 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/no_inner_declarations.rs | crates/rome_js_analyze/src/analyzers/correctness/no_inner_declarations.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{AnyJsDeclaration, JsFileSource, JsStatementList, JsSyntaxKind};
use rome_rowan::AstNode;
use crate::control_flow::AnyJsControlFlowRoot;
declare_rule! {
/// Disallow `function` and `var` declarations that are accessible outside their block.
///
/// A `var` is accessible in the whole body of the nearest root (function, module, script, static block).
/// To avoid confusion, they should be declared to the nearest root.
///
/// Prior to ES2015, `function` declarations were only allowed in the nearest root,
/// though parsers sometimes erroneously accept them elsewhere.
/// In ES2015, inside an _ES module_, a `function` declaration is always block-scoped.
///
/// Note that `const` and `let` declarations are block-scoped,
/// and therefore they are not affected by this rule.
/// Moreover, `function` declarations in nested blocks are allowed inside _ES modules_.
///
/// Source: https://eslint.org/docs/rules/no-inner-declarations
///
/// ## Examples
///
/// ### Invalid
///
/// ```cjs,expect_diagnostic
/// if (test) {
/// function f() {}
/// }
/// ```
///
/// ```js,expect_diagnostic
/// if (test) {
/// var x = 1;
/// }
/// ```
///
/// ```cjs,expect_diagnostic
/// function f() {
/// if (test) {
/// function g() {}
/// }
/// }
/// ```
///
/// ```js,expect_diagnostic
/// function f() {
/// if (test) {
/// var x = 1;
/// }
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// // inside a module, function declarations are block-scoped and thus allowed.
/// if (test) {
/// function f() {}
/// }
/// export {}
/// ```
///
/// ```js
/// function f() { }
/// ```
///
/// ```js
/// function f() {
/// function g() {}
/// }
/// ```
///
/// ```js
/// function f() {
/// var x = 1;
/// }
/// ```
///
/// ```js
/// function f() {
/// if (test) {
/// const g = function() {};
/// }
/// }
/// ```
///
pub(crate) NoInnerDeclarations {
version: "12.0.0",
name: "noInnerDeclarations",
recommended: true,
}
}
impl Rule for NoInnerDeclarations {
type Query = Ast<AnyJsDeclaration>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let decl = ctx.query();
let parent = match decl {
AnyJsDeclaration::TsDeclareFunctionDeclaration(x) => {
if ctx.source_type::<JsFileSource>().is_module() {
// In strict mode (implied by esm), function declarations are block-scoped.
return None;
}
// ignore TsDeclareStatement
x.syntax().parent()?.parent()?
}
AnyJsDeclaration::JsFunctionDeclaration(x) => {
if ctx.source_type::<JsFileSource>().is_module() {
// In strict mode (implied by esm), function declarations are block-scoped.
return None;
}
x.syntax().parent()?
}
AnyJsDeclaration::JsVariableDeclaration(x) => {
if !x.is_var() {
return None;
}
let mut parent = x.syntax().parent()?;
while matches!(
parent.kind(),
JsSyntaxKind::JS_VARIABLE_STATEMENT
| JsSyntaxKind::JS_VARIABLE_DECLARATION_CLAUSE
| JsSyntaxKind::TS_DECLARE_STATEMENT
) {
parent = parent.parent()?;
}
parent
}
_ => {
return None;
}
};
if matches!(
parent.kind(),
JsSyntaxKind::JS_EXPORT
| JsSyntaxKind::TS_EXPORT_DECLARE_CLAUSE
| JsSyntaxKind::JS_MODULE_ITEM_LIST
) {
return None;
}
if let Some(stmt_list) = JsStatementList::cast(parent) {
if matches!(
stmt_list.syntax().parent()?.kind(),
JsSyntaxKind::JS_FUNCTION_BODY
| JsSyntaxKind::JS_SCRIPT
| JsSyntaxKind::JS_STATIC_INITIALIZATION_BLOCK_CLASS_MEMBER
) {
return None;
}
}
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let decl = ctx.query();
let decl_type = match decl {
AnyJsDeclaration::JsFunctionDeclaration(_) => "function",
_ => "var",
};
let nearest_root = decl
.syntax()
.ancestors()
.skip(1)
.find_map(AnyJsControlFlowRoot::cast)?;
let nearest_root_type = match nearest_root {
AnyJsControlFlowRoot::JsModule(_) => "module",
AnyJsControlFlowRoot::JsScript(_) => "script",
AnyJsControlFlowRoot::JsStaticInitializationBlockClassMember(_) => "static block",
_ => "enclosing function",
};
Some(RuleDiagnostic::new(
rule_category!(),
decl.range(),
markup! {
"This "<Emphasis>{decl_type}</Emphasis>" should be declared at the root of the "<Emphasis>{nearest_root_type}</Emphasis>"."
},
).note(markup! {
"The "<Emphasis>{decl_type}</Emphasis>" is accessible in the whole body of the "<Emphasis>{nearest_root_type}</Emphasis>".\nTo avoid confusion, it should be declared at the root of the "<Emphasis>{nearest_root_type}</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/correctness/no_void_type_return.rs | crates/rome_js_analyze/src/analyzers/correctness/no_void_type_return.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{
AnyTsReturnType, JsArrowFunctionExpression, JsFunctionDeclaration,
JsFunctionExportDefaultDeclaration, JsFunctionExpression, JsGetterClassMember,
JsGetterObjectMember, JsMethodClassMember, JsMethodObjectMember, JsReturnStatement,
};
use rome_rowan::{declare_node_union, AstNode};
use crate::control_flow::AnyJsControlFlowRoot;
declare_rule! {
/// Disallow returning a value from a function with the return type 'void'
///
/// 'void' signals the absence of value. The returned value is likely to be ignored by the caller.
/// Thus, returning a value when the return type of function is 'void', is undoubtedly an error.
///
/// Only returning without a value is allowed, as it’s a control flow statement.
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// class A {
/// f(): void {
/// return undefined;
/// }
/// }
/// ```
///
/// ```ts,expect_diagnostic
/// const a = {
/// f(): void {
/// return undefined;
/// }
/// }
/// ```
///
/// ```ts,expect_diagnostic
/// function f(): void {
/// return undefined;
/// }
/// ```
///
/// ```ts,expect_diagnostic
/// export default function(): void {
/// return undefined;
/// }
/// ```
///
/// ```ts,expect_diagnostic
/// const g = (): void => {
/// return undefined;
/// };
/// ```
///
/// ```ts,expect_diagnostic
/// const h = function(): void {
/// return undefined;
/// };
/// ```
///
/// ### Valid
///
/// ```js
/// class A {
/// f() {
/// return undefined;
/// }
/// }
/// ```
///
/// ```ts
/// class B {
/// f(): void {}
/// }
/// ```
///
/// ```ts
/// function f(): void {
/// return;
/// }
/// ```
///
/// ```
pub(crate) NoVoidTypeReturn {
version: "11.0.0",
name: "noVoidTypeReturn",
recommended: true,
}
}
declare_node_union! {
pub(crate) JsFunctionMethod = JsArrowFunctionExpression | JsFunctionDeclaration | JsFunctionExportDefaultDeclaration | JsFunctionExpression | JsGetterClassMember | JsGetterObjectMember | JsMethodClassMember | JsMethodObjectMember
}
pub(crate) fn return_type(func: &JsFunctionMethod) -> Option<AnyTsReturnType> {
match func {
JsFunctionMethod::JsArrowFunctionExpression(func) => {
func.return_type_annotation()?.ty().ok()
}
JsFunctionMethod::JsFunctionDeclaration(func) => func.return_type_annotation()?.ty().ok(),
JsFunctionMethod::JsFunctionExportDefaultDeclaration(func) => {
func.return_type_annotation()?.ty().ok()
}
JsFunctionMethod::JsFunctionExpression(func) => func.return_type_annotation()?.ty().ok(),
JsFunctionMethod::JsGetterClassMember(func) => {
Some(AnyTsReturnType::AnyTsType(func.return_type()?.ty().ok()?))
}
JsFunctionMethod::JsGetterObjectMember(func) => {
Some(AnyTsReturnType::AnyTsType(func.return_type()?.ty().ok()?))
}
JsFunctionMethod::JsMethodClassMember(func) => func.return_type_annotation()?.ty().ok(),
JsFunctionMethod::JsMethodObjectMember(func) => func.return_type_annotation()?.ty().ok(),
}
}
impl Rule for NoVoidTypeReturn {
type Query = Ast<JsReturnStatement>;
type State = JsFunctionMethod;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let ret = ctx.query();
// Do not take arg-less returns into account
let _arg = ret.argument()?;
let func = ret
.syntax()
.ancestors()
.find(|x| AnyJsControlFlowRoot::can_cast(x.kind()))
.and_then(JsFunctionMethod::cast)?;
let ret_type = return_type(&func)?;
ret_type.as_any_ts_type()?.as_ts_void_type().and(Some(func))
}
fn diagnostic(ctx: &RuleContext<Self>, func: &Self::State) -> Option<RuleDiagnostic> {
let ret = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
ret.range(),
markup! {
"The function should not "<Emphasis>"return"</Emphasis>" a value because its return type is "<Emphasis>"void"</Emphasis>"."
},
).detail(func.range(), "The function is here:").note(
"'void' signals the absence of value. The returned value is likely to be ignored by the caller."
))
}
}
| 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/no_unreachable.rs | crates/rome_js_analyze/src/analyzers/correctness/no_unreachable.rs | use std::{cmp::Ordering, collections::VecDeque, num::NonZeroU32, vec::IntoIter};
use roaring::bitmap::RoaringBitmap;
use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic};
use rome_control_flow::{
builder::BlockId, ExceptionHandler, ExceptionHandlerKind, Instruction, InstructionKind,
};
use rome_js_syntax::{
JsBlockStatement, JsCaseClause, JsDefaultClause, JsDoWhileStatement, JsForInStatement,
JsForOfStatement, JsForStatement, JsFunctionBody, JsIfStatement, JsLabeledStatement,
JsLanguage, JsReturnStatement, JsSwitchStatement, JsSyntaxElement, JsSyntaxKind, JsSyntaxNode,
JsTryFinallyStatement, JsTryStatement, JsVariableStatement, JsWhileStatement, TextRange,
};
use rome_rowan::{declare_node_union, AstNode};
use rustc_hash::FxHashMap;
use crate::control_flow::{ControlFlowGraph, JsControlFlowGraph};
declare_rule! {
/// Disallow unreachable code
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// function example() {
/// return;
/// neverCalled();
/// }
/// ```
///
/// ```js,expect_diagnostic
/// function example() {
/// for(let i = 0; i < 10; ++i) {
/// break;
/// }
/// }
/// ```
///
/// ```js,expect_diagnostic
/// function example() {
/// for(const key in value) {
/// continue;
/// neverCalled();
/// }
/// }
/// ```
pub(crate) NoUnreachable {
version: "0.7.0",
name: "noUnreachable",
recommended: true,
}
}
impl Rule for NoUnreachable {
type Query = ControlFlowGraph;
type State = UnreachableRange;
type Signals = UnreachableRanges;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let mut signals = UnreachableRanges::new();
let cfg = ctx.query();
if exceeds_complexity_threshold(cfg) {
analyze_simple(cfg, &mut signals)
} else {
analyze_fine(cfg, &mut signals)
}
signals
}
fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let mut diagnostic = RuleDiagnostic::new(
rule_category!(),
state.text_trimmed_range,
if state.terminators.is_empty() {
"This code is unreachable"
} else {
"This code will never be reached ..."
},
)
.description("This code is unreachable")
.unnecessary();
// Pluralize and adapt the error message accordingly based on the
// number and position of secondary labels
match state.terminators.as_slice() {
// The CFG didn't contain enough informations to determine a cause
// for this range being unreachable
[] => {}
// A single node is responsible for this range being unreachable
[node] => {
diagnostic = diagnostic.detail(
node.range,
format_args!(
"... because this statement will {} beforehand",
node.reason()
),
);
}
// The range has two dominating terminator instructions
[node_a, node_b] => {
if node_a.kind == node_b.kind {
diagnostic = diagnostic
.detail(node_a.range, "... because either this statement ...")
.detail(
node_b.range,
format_args!(
"... or this statement will {} beforehand",
node_b.reason()
),
);
} else {
diagnostic = diagnostic
.detail(
node_a.range,
format_args!(
"... because either this statement will {} ...",
node_a.reason()
),
)
.detail(
node_b.range,
format_args!(
"... or this statement will {} beforehand",
node_b.reason()
),
);
}
}
// The range has three or more dominating terminator instructions
terminators => {
// SAFETY: This substraction is safe since the match expression
// ensures the slice has at least 3 elements
let last = terminators.len() - 1;
// Do not repeat the reason for each terminator if they all have the same kind
let (_, has_homogeneous_kind) = terminators
.iter()
.fold(None, |prev_kind, terminator| match prev_kind {
Some((kind, state)) => Some((kind, state && terminator.kind == kind)),
None => Some((terminator.kind, true)),
})
// SAFETY: terminators has at least 3 elements
.unwrap();
if has_homogeneous_kind {
for (index, node) in terminators.iter().enumerate() {
if index == 0 {
diagnostic = diagnostic
.detail(node.range, "... because either this statement, ...");
} else if index < last {
diagnostic = diagnostic.detail(node.range, "... this statement, ...");
} else {
diagnostic = diagnostic.detail(
node.range,
format_args!(
"... or this statement will {} beforehand",
node.reason()
),
);
}
}
} else {
for (index, node) in terminators.iter().enumerate() {
if index == 0 {
diagnostic = diagnostic.detail(
node.range,
format_args!(
"... because either this statement will {}, ...",
node.reason()
),
);
} else if index < last {
diagnostic = diagnostic.detail(
node.range,
format_args!("... this statement will {}, ...", node.reason()),
);
} else {
diagnostic = diagnostic.detail(
node.range,
format_args!(
"... or this statement will {} beforehand",
node.reason()
),
);
}
}
}
}
}
Some(diagnostic)
}
}
/// Any function with a complexity score higher than this value will use the
/// simple reachability analysis instead of the fine analysis
const COMPLEXITY_THRESHOLD: u32 = 20;
/// Returns true if the "complexity score" for the [JsControlFlowGraph] is higher
/// than [COMPLEXITY_THRESHOLD]. This score is an arbritrary value (the formula
/// is similar to the cyclomatic complexity of the function but this is only
/// approximative) used to determine whether the NoDeadCode rule should perform
/// a fine reachability analysis or fall back to a simpler algorithm to avoid
/// spending too much time analyzing exceedingly complex functions
fn exceeds_complexity_threshold(cfg: &JsControlFlowGraph) -> bool {
let nodes = cfg.blocks.len() as u32;
let mut edges: u32 = 0;
let mut conditionals: u32 = 0;
for block in &cfg.blocks {
let mut exception_handlers = NonZeroU32::new(block.exception_handlers.len() as u32);
let mut cleanup_handlers = NonZeroU32::new(block.cleanup_handlers.len() as u32);
for inst in &block.instructions {
if has_side_effects(inst) {
if let Some(handlers) = exception_handlers.take() {
edges += handlers.get();
conditionals += 1;
}
}
match inst.kind {
InstructionKind::Statement => {}
InstructionKind::Jump { conditional, .. } => {
edges += 1;
if conditional {
conditionals += 1;
}
}
InstructionKind::Return => {
if let Some(handlers) = cleanup_handlers.take() {
edges += handlers.get();
conditionals += 1;
}
}
}
let complexity = edges.saturating_sub(nodes) + conditionals / 2;
if complexity > COMPLEXITY_THRESHOLD {
return true;
}
}
}
false
}
/// Perform a simple reachability analysis, does not attempt to determine a
/// terminator instruction for unreachable ranges allowing blocks to be visited
/// at most once and ensuring the algorithm finishes in a bounded time
fn analyze_simple(cfg: &JsControlFlowGraph, signals: &mut UnreachableRanges) {
// Perform a simple reachability analysis on the control flow graph by
// traversing the function starting at the entry point
let mut reachable_blocks = RoaringBitmap::new();
let mut queue = VecDeque::new();
if !cfg.blocks.is_empty() {
reachable_blocks.insert(0);
queue.push_back((0, None));
}
while let Some((index, handlers)) = queue.pop_front() {
let index = index as usize;
let block = &cfg.blocks[index];
// Lookup the existence of an exception edge for this block but
// defer its creation until an instruction that can throw is encountered
let mut exception_handlers = block.exception_handlers.split_first();
// Tracks whether this block is "terminated", if an instruction
// that unconditionally aborts the control flow of this block has
// been encountered
let mut has_terminator = false;
for inst in &block.instructions {
// If this block is terminated, mark this instruction as unreachable and continue
if has_terminator {
if let Some(node) = &inst.node {
signals.push(node, None);
}
continue;
}
// Do not create exception edges for instructions with no side effects
if has_side_effects(inst) {
// If this block has a pending exception edge, create an
// additional path diverging towards the corresponding
// catch or finally block
if let Some((handler, handlers)) = exception_handlers.take() {
if reachable_blocks.insert(handler.target) {
queue.push_back((handler.target, find_catch_handlers(handlers)));
}
}
}
match inst.kind {
InstructionKind::Statement => {}
InstructionKind::Jump {
conditional,
block,
finally_fallthrough,
} => {
if finally_fallthrough && handlers.is_some() {
// Jump towards the corresponding block if there are pending exception
// handlers, otherwise return from the function
let handlers = handlers.and_then(<[_]>::split_first);
if let Some((handler, handlers)) = handlers {
if reachable_blocks.insert(handler.target) {
queue.push_back((handler.target, Some(handlers)));
}
}
} else if reachable_blocks.insert(block.index()) {
// Insert an edge if this jump is reachable
queue.push_back((block.index(), handlers));
}
// Jump is a terminator instruction if it's unconditional
if !conditional {
has_terminator = true;
}
}
InstructionKind::Return => {
if let Some((handler, handlers)) = block.cleanup_handlers.split_first() {
if reachable_blocks.insert(handler.target) {
queue.push_back((handler.target, Some(handlers)));
}
}
has_terminator = true;
}
}
}
}
// Detect blocks that were never reached by the above traversal
for (index, block) in cfg.blocks.iter().enumerate() {
let index = index as u32;
if reachable_blocks.contains(index) {
continue;
}
for inst in &block.instructions {
if let Some(node) = &inst.node {
signals.push(node, None);
}
}
}
}
/// Performs a fine reachability analysis of the control flow graph: this
/// algorithm traverse all the possible paths through the function to determine
/// the reachability of each block and instruction but also find one or more
/// "terminator instructions" for each unreachable range of code that cause it
/// to be impossible to reach
fn analyze_fine(cfg: &JsControlFlowGraph, signals: &mut UnreachableRanges) {
// Traverse the CFG and calculate block / instruction reachability
let block_paths = traverse_cfg(cfg, signals);
// Detect unreachable blocks using the result of the above traversal
'blocks: for (index, block) in cfg.blocks.iter().enumerate() {
let index = index as u32;
match block_paths.get(&index) {
// Block has incoming paths, but may be unreachable if they all
// have a dominating terminator intruction
Some(paths) => {
let mut terminators = Vec::new();
for path in paths {
if let Some(terminator) = *path {
terminators.push(terminator);
} else {
// This path has no terminator, the block is reachable
continue 'blocks;
}
}
// Mark each instruction in the block as unreachable with
// the appropriate terminator labels
for inst in &block.instructions {
if let Some(node) = &inst.node {
for terminator in &terminators {
signals.push(node, *terminator);
}
}
}
}
// Block has no incoming paths, is completely cut off from the CFG
// In theory this shouldn't happen as our CFG also stores
// unreachable edges, if we get here there might be a bug in
// the control flow analysis
None => {
for inst in &block.instructions {
if let Some(node) = &inst.node {
// There is no incoming control flow so we can't
// determine a terminator instruction for this
// unreachable range
signals.push(node, None);
}
}
}
}
}
}
/// Individual entry in the traversal queue, holding the state for a
/// single "linearly independent path" through the function as it gets
/// created during the control flow traversal
struct PathState<'cfg> {
/// Index of the next block to visit
next_block: u32,
/// Set of all blocks already visited on this path
visited: RoaringBitmap,
/// Current terminating instruction for the path, if one was
/// encountered
terminator: Option<Option<PathTerminator>>,
exception_handlers: Option<&'cfg [ExceptionHandler]>,
}
/// Perform a simple reachability analysis on the control flow graph by
/// traversing the function starting at the entry points
fn traverse_cfg(
cfg: &JsControlFlowGraph,
signals: &mut UnreachableRanges,
) -> FxHashMap<u32, Vec<Option<Option<PathTerminator>>>> {
let mut queue = VecDeque::new();
queue.push_back(PathState {
next_block: 0,
visited: RoaringBitmap::new(),
terminator: None,
exception_handlers: None,
});
// This maps holds a list of "path state", the active terminator
// intruction for each path that can reach the block
let mut block_paths = FxHashMap::default();
while let Some(mut path) = queue.pop_front() {
// Add the block to the visited set for the path, and the current
// state of the path to the global reachable blocks map
path.visited.insert(path.next_block);
block_paths
.entry(path.next_block)
.or_insert_with(Vec::new)
.push(path.terminator);
let index = path.next_block as usize;
let block = &cfg.blocks[index];
// Lookup the existence of an exception edge for this block but
// defer its creation until an instruction that can throw is encountered
let mut exception_handlers = block.exception_handlers.split_first();
// Set to true if the `terminator` is found inside of this block
let mut has_direct_terminator = false;
for inst in &block.instructions {
// Do not create exception edges for instructions with no side effects
if has_side_effects(inst) {
// If this block has a pending exception edge, create an
// additional path diverging towards the corresponding
// catch or finally block
if let Some((handler, handlers)) = exception_handlers.take() {
if !path.visited.contains(handler.target) {
queue.push_back(PathState {
next_block: handler.target,
visited: path.visited.clone(),
terminator: path.terminator,
exception_handlers: find_catch_handlers(handlers),
});
}
}
}
// If this block has already ended, immediately mark this instruction as unreachable
if let Some(terminator) = path.terminator.filter(|_| has_direct_terminator) {
if let Some(node) = &inst.node {
signals.push(node, terminator);
}
}
match inst.kind {
InstructionKind::Statement => {}
InstructionKind::Jump {
conditional,
block,
finally_fallthrough,
} => {
handle_jump(&mut queue, &path, block, finally_fallthrough);
// Jump is a terminator instruction if it's unconditional
if path.terminator.is_none() && !conditional {
path.terminator = Some(inst.node.as_ref().map(|node| PathTerminator {
kind: node.kind(),
range: node.text_trimmed_range(),
}));
has_direct_terminator = true;
}
}
InstructionKind::Return => {
handle_return(&mut queue, &path, &block.cleanup_handlers);
if path.terminator.is_none() {
path.terminator = Some(inst.node.as_ref().map(|node| PathTerminator {
kind: node.kind(),
range: node.text_trimmed_range(),
}));
has_direct_terminator = true;
}
}
}
}
}
block_paths
}
/// Returns `true` if `inst` can potentially have side effects. Due to the
/// dynamic nature of JavaScript this is a conservative check, biased towards
/// returning false positives
fn has_side_effects(inst: &Instruction<JsLanguage>) -> bool {
let element = match inst.node.as_ref() {
Some(element) => element,
None => return false,
};
match element.kind() {
JsSyntaxKind::JS_RETURN_STATEMENT => {
let node = JsReturnStatement::unwrap_cast(element.as_node().unwrap().clone());
node.argument().is_some()
}
JsSyntaxKind::JS_BREAK_STATEMENT | JsSyntaxKind::JS_CONTINUE_STATEMENT => false,
kind => element.as_node().is_some() && !kind.is_literal(),
}
}
/// Returns the list of all `finally` exception handlers up to and including
/// the first `catch` handler to be executed when an exception is thrown
fn find_catch_handlers(handlers: &[ExceptionHandler]) -> Option<&[ExceptionHandler]> {
let handlers = handlers
.iter()
.position(|handler| matches!(handler.kind, ExceptionHandlerKind::Catch))
.map(|index| &handlers[index..])
.unwrap_or(handlers);
if handlers.is_empty() {
None
} else {
Some(handlers)
}
}
/// Create an additional visitor path from a jump instruction and push it to the queue
fn handle_jump<'cfg>(
queue: &mut VecDeque<PathState<'cfg>>,
path: &PathState<'cfg>,
block: BlockId,
finally_fallthrough: bool,
) {
// If this jump is exiting a finally clause and and this path is visiting
// an exception handlers chain
if finally_fallthrough && path.exception_handlers.is_some() {
// Jump towards the corresponding block if there are pending exception
// handlers, otherwise return from the function
let handlers = path.exception_handlers.and_then(<[_]>::split_first);
if let Some((handler, handlers)) = handlers {
if !path.visited.contains(handler.target) {
queue.push_back(PathState {
next_block: handler.target,
visited: path.visited.clone(),
terminator: path.terminator,
exception_handlers: Some(handlers),
});
}
}
} else if !path.visited.contains(block.index()) {
// Push the jump target block to the queue if it hasn't
// been visited yet in this path
queue.push_back(PathState {
next_block: block.index(),
visited: path.visited.clone(),
terminator: path.terminator,
exception_handlers: path.exception_handlers,
});
}
}
/// Create an additional visitor path from a return instruction and push it to
/// the queue if necessary
fn handle_return<'cfg>(
queue: &mut VecDeque<PathState<'cfg>>,
path: &PathState<'cfg>,
cleanup_handlers: &'cfg [ExceptionHandler],
) {
if let Some((handler, handlers)) = cleanup_handlers.split_first() {
if !path.visited.contains(handler.target) {
queue.push_back(PathState {
next_block: handler.target,
visited: path.visited.clone(),
terminator: path.terminator,
exception_handlers: Some(handlers),
});
}
}
}
/// Stores a list of unreachable code ranges, sorted in ascending source order
#[derive(Debug)]
pub(crate) struct UnreachableRanges {
ranges: Vec<UnreachableRange>,
}
impl UnreachableRanges {
fn new() -> Self {
UnreachableRanges { ranges: Vec::new() }
}
fn push(&mut self, node: &JsSyntaxElement, terminator: Option<PathTerminator>) {
let text_range = node.text_range();
let text_trimmed_range = node.text_trimmed_range();
// Perform a binary search on the ranges already in storage to find an
// appropriate position for either merging or inserting the incoming range
let insertion = self.ranges.binary_search_by(|entry| {
if entry.text_range.end() < text_range.start() {
Ordering::Less
} else if text_range.end() < entry.text_range.start() {
Ordering::Greater
} else {
Ordering::Equal
}
});
let index = match insertion {
// The search returned an existing overlapping range, extend it to
// cover the incoming range
Ok(index) => {
let entry = &mut self.ranges[index];
entry.text_range = entry.text_range.cover(text_range);
entry.text_trimmed_range = entry.text_trimmed_range.cover(text_trimmed_range);
if let Some(terminator) = terminator {
// Terminator labels are also stored in ascending order to
// faciliate the generation of labels when the diagnostic
// gets emitted
let terminator_insertion = entry
.terminators
.binary_search_by_key(&terminator.range.start(), |node| node.range.start());
if let Err(index) = terminator_insertion {
entry.terminators.insert(index, terminator);
}
}
index
}
// No overlapping range was found, insert at the appropriate
// position to preserve the ordering instead
Err(index) => {
self.ranges.insert(
index,
UnreachableRange {
text_range,
text_trimmed_range,
terminators: terminator.into_iter().collect(),
},
);
index
}
};
let node = match node.parent() {
Some(parent) => parent,
None => return,
};
self.propagate_ranges(node, index);
}
/// Propagate unreachable ranges upward in the tree by detecting and
/// merging disjoint ranges that cover all the fields of a certain node
/// type. This requires specialized logic for each control flow node type,
/// for instance an if-statement is considered fully unreachable if its
/// test expression, consequent statement and optional else clause are all
/// fully unreachable.
fn propagate_ranges(&mut self, mut node: JsSyntaxNode, mut index: usize) -> Option<()> {
while let Some(parent) = node.ancestors().find_map(JsControlFlowNode::cast) {
// Merge the adjacent and overlapping ranges
self.merge_adjacent_ranges();
let fields = match &parent {
JsControlFlowNode::JsFunctionBody(_) => break,
JsControlFlowNode::JsBlockStatement(stmt) => {
let statements = stmt.statements().into_syntax();
if statements.text_trimmed_range().is_empty() {
vec![]
} else {
vec![statements.text_range()]
}
}
JsControlFlowNode::JsVariableStatement(stmt) => {
let declaration = stmt.declaration().ok()?;
declaration
.declarators()
.into_iter()
.filter_map(|declarator| match declarator {
Ok(declarator) => match declarator.initializer()?.expression() {
Ok(expression) => Some(Ok(expression.syntax().text_range())),
Err(err) => Some(Err(err)),
},
Err(err) => Some(Err(err)),
})
.collect::<Result<Vec<_>, _>>()
.ok()?
}
JsControlFlowNode::JsLabeledStatement(stmt) => {
vec![stmt.body().ok()?.syntax().text_range()]
}
JsControlFlowNode::JsDoWhileStatement(stmt) => vec![
stmt.body().ok()?.syntax().text_range(),
stmt.test().ok()?.syntax().text_range(),
],
JsControlFlowNode::JsForInStatement(stmt) => vec![
stmt.initializer().ok()?.syntax().text_range(),
stmt.body().ok()?.syntax().text_range(),
],
JsControlFlowNode::JsForOfStatement(stmt) => vec![
stmt.initializer().ok()?.syntax().text_range(),
stmt.body().ok()?.syntax().text_range(),
],
JsControlFlowNode::JsForStatement(stmt) => {
let mut res = Vec::new();
if let Some(initializer) = stmt.initializer() {
res.push(initializer.syntax().text_range());
}
if let Some(test) = stmt.test() {
res.push(test.syntax().text_range());
}
if let Some(update) = stmt.update() {
res.push(update.syntax().text_range());
}
res.push(stmt.body().ok()?.syntax().text_range());
res
}
JsControlFlowNode::JsIfStatement(stmt) => {
let mut res = vec![
stmt.test().ok()?.syntax().text_range(),
stmt.consequent().ok()?.syntax().text_range(),
];
if let Some(else_clause) = stmt.else_clause() {
res.push(else_clause.alternate().ok()?.syntax().text_range());
}
res
}
JsControlFlowNode::JsSwitchStatement(stmt) => {
let mut res = vec![stmt.discriminant().ok()?.syntax().text_range()];
let cases = stmt.cases().into_syntax();
if !cases.text_trimmed_range().is_empty() {
res.push(cases.text_range());
}
res
}
JsControlFlowNode::JsTryStatement(stmt) => vec![
stmt.body().ok()?.syntax().text_range(),
stmt.catch_clause().ok()?.body().ok()?.syntax().text_range(),
],
JsControlFlowNode::JsTryFinallyStatement(stmt) => {
let mut res = vec![stmt.body().ok()?.syntax().text_range()];
if let Some(catch_clause) = stmt.catch_clause() {
res.push(catch_clause.body().ok()?.syntax().text_range());
}
res.push(
stmt.finally_clause()
.ok()?
.body()
.ok()?
.syntax()
.text_range(),
);
res
}
JsControlFlowNode::JsWhileStatement(stmt) => vec![
stmt.test().ok()?.syntax().text_range(),
stmt.body().ok()?.syntax().text_range(),
],
JsControlFlowNode::JsCaseClause(stmt) => {
let mut res = vec![stmt.test().ok()?.syntax().text_range()];
let consequent = stmt.consequent().into_syntax();
if !consequent.text_trimmed_range().is_empty() {
res.push(consequent.text_range());
}
res
}
JsControlFlowNode::JsDefaultClause(stmt) => {
let mut res = vec![stmt.default_token().ok()?.text_range()];
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/correctness/no_empty_pattern.rs | crates/rome_js_analyze/src/analyzers/correctness/no_empty_pattern.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{JsArrayBindingPattern, JsObjectBindingPattern};
use rome_rowan::{declare_node_union, AstNode, AstSeparatedList};
declare_rule! {
/// Disallows empty destructuring patterns.
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// var {} = foo;
/// ```
///
/// ```js,expect_diagnostic
/// var {a: {}} = foo;
/// ```
///
/// ```js,expect_diagnostic
/// function foo({}) {}
/// ```
///
/// ### Valid
/// The following cases are valid because they create new bindings.
///
/// ```js
/// var {a = {}} = foo;
/// var {a, b = {}} = foo;
/// var {a = []} = foo;
/// function foo({a = {}}) {}
/// function foo({a = []}) {}
/// var [a] = foo;
/// ```
pub(crate) NoEmptyPattern {
version: "0.7.0",
name: "noEmptyPattern",
recommended: true,
}
}
impl Rule for NoEmptyPattern {
type Query = Ast<JsAnyBindPatternLike>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
use JsAnyBindPatternLike::*;
match ctx.query() {
JsArrayBindingPattern(array) => {
if array.elements().len() == 0 {
Some(())
} else {
None
}
}
JsObjectBindingPattern(object) => {
if object.properties().len() == 0 {
Some(())
} else {
None
}
}
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
let node_type = match node {
JsAnyBindPatternLike::JsArrayBindingPattern(_) => "array",
JsAnyBindPatternLike::JsObjectBindingPattern(_) => "object",
};
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Unexpected empty "{node_type}" pattern."
},
))
}
}
declare_node_union! {
/// enum of `JsObjectBindingPattern` and `JsArrayBindingPattern`
pub(crate) JsAnyBindPatternLike = JsArrayBindingPattern | JsObjectBindingPattern
}
| 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/no_switch_declarations.rs | crates/rome_js_analyze/src/analyzers/correctness/no_switch_declarations.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::{
AnyJsDeclaration, AnyJsStatement, AnyJsSwitchClause, JsSyntaxNode, JsVariableStatement,
TriviaPieceKind, T,
};
use rome_rowan::{AstNode, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Disallow lexical declarations in `switch` clauses.
///
/// Lexical declarations in `switch` clauses are accessible in the entire `switch`.
/// However, it only gets initialized when it is assigned, which will only happen if the `switch` clause where it is defined is reached.
///
/// To ensure that the lexical declarations only apply to the current `switch` clause wrap your declarations in a block.
///
/// Source: https://eslint.org/docs/latest/rules/no-case-declarations
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// switch (foo) {
/// case 0:
/// const x = 1;
/// break;
/// case 2:
/// x; // `x` can be used while it is not initialized
/// break;
/// }
/// ```
///
/// ```js,expect_diagnostic
/// switch (foo) {
/// case 0:
/// function f() {}
/// break;
/// case 2:
/// f(); // `f` can be called here
/// break;
/// }
/// ```
///
/// ```js,expect_diagnostic
/// switch (foo) {
/// case 0:
/// class A {}
/// break;
/// default:
/// new A(); // `A` can be instantiated here
/// break;
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// switch (foo) {
/// case 0: {
/// const x = 1;
/// break;
/// }
/// case 1:
/// // `x` is not visible here
/// break;
/// }
/// ```
///
pub(crate) NoSwitchDeclarations {
version: "12.0.0",
name: "noSwitchDeclarations",
recommended: true,
}
}
fn declaration_cast(node: JsSyntaxNode) -> Option<AnyJsDeclaration> {
if JsVariableStatement::can_cast(node.kind()) {
Some(AnyJsDeclaration::JsVariableDeclaration(
JsVariableStatement::cast(node)?.declaration().ok()?,
))
} else {
AnyJsDeclaration::cast(node)
}
}
impl Rule for NoSwitchDeclarations {
type Query = Ast<AnyJsSwitchClause>;
type State = AnyJsDeclaration;
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let switch_clause = ctx.query();
switch_clause
.consequent()
.syntax()
.children()
.filter_map(declaration_cast)
.collect()
}
fn diagnostic(ctx: &RuleContext<Self>, decl: &Self::State) -> Option<RuleDiagnostic> {
let switch_clause = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
decl.range(),
markup! {
"Other switch clauses can erroneously access this "<Emphasis>"declaration"</Emphasis>".\nWrap the declaration in a block to restrict its access to the switch clause."
},
).detail(switch_clause.range(), markup! {
"The declaration is defined in this "<Emphasis>"switch clause"</Emphasis>":"
}))
}
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(Some((TriviaPieceKind::Whitespace, " ")))
.with_trailing_trivia_pieces(colon_token.trailing_trivia().pieces()),
consequent.to_owned(),
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 "<Emphasis>"declaration"</Emphasis>" 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/correctness/no_unnecessary_continue.rs | crates/rome_js_analyze/src/analyzers/correctness/no_unnecessary_continue.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{JsContinueStatement, JsLabeledStatement, JsSyntaxKind, JsSyntaxNode};
use rome_rowan::{AstNode, BatchMutationExt};
use crate::{utils, JsRuleAction};
declare_rule! {
/// Avoid using unnecessary `continue`.
///
/// ## Examples
///
/// ### Invalid
/// ```js,expect_diagnostic
/// loop: for (let i = 0; i < 5; i++) {
/// continue loop;
/// }
/// ```
/// ```js,expect_diagnostic
/// while (i--) {
/// continue;
/// }
/// ```
/// ```js,expect_diagnostic
/// while (1) {
/// continue;
/// }
/// ```
/// ```js,expect_diagnostic
/// for (let i = 0; i < 10; i++) {
/// if (i > 5) {
/// console.log("foo");
/// continue;
/// } else if (i >= 5 && i < 8) {
/// console.log("test");
/// } else {
/// console.log("test");
/// }
/// }
/// ```
/// ```js,expect_diagnostic
/// for (let i = 0; i < 9; i++) {
/// continue;
/// }
/// ```
///
/// ```js, expect_diagnostic
/// test2: do {
/// continue test2;
/// } while (true);
/// ```
///
/// ### Valid
/// ```js
/// while (i) {
/// if (i > 5) {
/// continue;
/// }
/// console.log(i);
/// i--;
/// }
///
/// loop: while (1) {
/// forLoop: for (let i = 0; i < 5; i++) {
/// if (someCondition) {
/// continue loop;
/// }
/// }
/// }
/// ```
pub(crate) NoUnnecessaryContinue {
version: "0.7.0",
name: "noUnnecessaryContinue",
recommended: true,
}
}
impl Rule for NoUnnecessaryContinue {
type Query = Ast<JsContinueStatement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
is_continue_un_necessary(node)?.then_some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Unnecessary continue statement"
},
))
}
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! { "Delete the unnecessary continue statement" }.to_owned(),
mutation,
})
}
}
fn is_continue_un_necessary(node: &JsContinueStatement) -> Option<bool> {
use rome_js_syntax::JsSyntaxKind::*;
let syntax = node.clone().into_syntax();
let mut current = syntax.clone();
let mut ancestors = vec![];
let mut loop_stmt = None;
while let Some(parent) = current.parent() {
if !matches!(
parent.kind(),
JS_FOR_IN_STATEMENT
| JS_FOR_OF_STATEMENT
| JS_FOR_STATEMENT
| JS_WHILE_STATEMENT
| JS_DO_WHILE_STATEMENT
) {
ancestors.push(parent.clone());
} else {
loop_stmt = Some(parent);
break;
}
current = parent;
}
let loop_stmt = loop_stmt?;
if ancestors.is_empty() {
return Some(true);
}
Some(
is_continue_last_statement(&ancestors, syntax.clone()).unwrap_or(false)
&& contains_parent_loop_label(syntax.clone(), loop_stmt).unwrap_or(false)
&& is_continue_inside_last_ancestors(&ancestors, syntax).unwrap_or(false),
)
}
fn is_continue_last_statement(ancestors: &[JsSyntaxNode], syntax: JsSyntaxNode) -> Option<bool> {
let first_node = ancestors.first()?;
if first_node.kind() == JsSyntaxKind::JS_STATEMENT_LIST {
Some(first_node.children().last()? == syntax)
} else {
None
}
}
/// return true if continue label is undefined or equal to its parent's looplabel
fn contains_parent_loop_label(node: JsSyntaxNode, loop_stmt: JsSyntaxNode) -> Option<bool> {
let continue_stmt = JsContinueStatement::cast(node)?;
let continue_stmt_label = continue_stmt.label_token();
if let Some(label) = continue_stmt_label {
let label_stmt = JsLabeledStatement::cast(loop_stmt.parent()?)?;
Some(label_stmt.label_token().ok()?.text_trimmed() == label.text_trimmed())
} else {
Some(true)
}
}
fn is_continue_inside_last_ancestors(
ancestors: &[JsSyntaxNode],
syntax: JsSyntaxNode,
) -> Option<bool> {
let len = ancestors.len();
for ancestor_window in ancestors.windows(2).rev() {
let parent = &ancestor_window[1];
let child = &ancestor_window[0];
if parent.kind() == JsSyntaxKind::JS_STATEMENT_LIST {
let body = parent.children();
let last_body_node = body.last()?;
if !((len == 1 && last_body_node == syntax) || (len > 1 && &last_body_node == child)) {
return Some(false);
}
}
}
Some(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/correctness/no_unsafe_optional_chaining.rs | crates/rome_js_analyze/src/analyzers/correctness/no_unsafe_optional_chaining.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{
AnyJsAssignmentPattern, AnyJsBindingPattern, AnyJsExpression, JsAssignmentExpression,
JsAssignmentWithDefault, JsAwaitExpression, JsCallExpression, JsComputedMemberExpression,
JsConditionalExpression, JsExtendsClause, JsForOfStatement, JsInExpression,
JsInitializerClause, JsInstanceofExpression, JsLogicalExpression, JsLogicalOperator,
JsNewExpression, JsObjectAssignmentPatternProperty, JsObjectMemberList,
JsParenthesizedExpression, JsSequenceExpression, JsSpread, JsStaticMemberExpression,
JsTemplateExpression, JsVariableDeclarator, JsWithStatement,
};
use rome_rowan::{declare_node_union, AstNode, TextRange};
declare_rule! {
/// Disallow the use of optional chaining in contexts where the undefined value is not allowed.
///
/// The optional chaining (?.) expression can short-circuit with a return value of undefined.
/// Therefore, treating an evaluated optional chaining expression as a function, object, number, etc., can cause TypeError or unexpected results.
/// Also, parentheses limit the scope of short-circuiting in chains.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// 1 in obj?.foo;
/// ```
///
/// ```cjs,expect_diagnostic
/// with (obj?.foo);
/// ```
///
/// ```js,expect_diagnostic
/// for (bar of obj?.foo);
/// ```
///
/// ```js,expect_diagnostic
/// bar instanceof obj?.foo;
/// ```
///
/// ```js,expect_diagnostic
/// const { bar } = obj?.foo;
/// ```
///
/// ```js,expect_diagnostic
/// (obj?.foo)();
/// ```
///
/// ```js,expect_diagnostic
/// (baz?.bar).foo;
/// ```
///
/// ## Valid
///
/// ```js
/// (obj?.foo)?.();
/// obj?.foo();
/// (obj?.foo ?? bar)();
/// obj?.foo.bar;
/// obj.foo?.bar;
/// foo?.()?.bar;
/// ```
///
pub(crate) NoUnsafeOptionalChaining {
version: "12.0.0",
name: "noUnsafeOptionalChaining",
recommended: true,
}
}
impl Rule for NoUnsafeOptionalChaining {
type Query = Ast<QueryNode>;
type State = TextRange;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let query_node = ctx.query();
// need to check only optional chain nodes
if !query_node.is_optional() {
return None;
}
let mut node: RuleNode = query_node.clone().into();
let mut parent = node.parent::<RuleNode>();
// parentheses limit the scope of short-circuiting in chains
// (a?.b).c // here we have an error
// a?.b.c // ok
let mut is_inside_parenthesis = false;
while let Some(current_parent) = parent.take() {
match ¤t_parent {
RuleNode::JsParenthesizedExpression(expression) => {
// parentheses limit the scope of short-circuiting in chains
is_inside_parenthesis = true;
parent = expression.parent::<RuleNode>()
}
RuleNode::JsAwaitExpression(expression) => parent = expression.parent::<RuleNode>(),
RuleNode::JsExtendsClause(extends) => {
// class A extends obj?.foo {}
return Some(extends.syntax().text_trimmed_range());
}
RuleNode::JsNewExpression(expression) => {
// If we're here, it means we've found a error
// new a?.b
// new (a?.b)()
return Some(expression.syntax().text_trimmed_range());
}
RuleNode::JsLogicalExpression(expression) => {
match expression.operator().ok()? {
JsLogicalOperator::NullishCoalescing | JsLogicalOperator::LogicalOr => {
// for logical or and nullish we need to check only the right expression
// (a?.b || a?.b).c()
if expression.right().ok()?.syntax() == node.syntax() {
parent = expression.parent::<RuleNode>()
}
}
// for logical and we need check both branches
// (a?.b && a?.b).c()
JsLogicalOperator::LogicalAnd => parent = expression.parent::<RuleNode>(),
}
}
RuleNode::JsSequenceExpression(expression) => {
let is_last_in_sequence = expression.parent::<JsSequenceExpression>().is_none();
// need to check only the rightmost expression in the sequence
// a, b, c?.()
if is_last_in_sequence && expression.right().ok()?.syntax() == node.syntax() {
parent = expression.parent::<RuleNode>()
}
}
RuleNode::JsConditionalExpression(expression) => {
// need to check consequent and alternate branches
// (a ? obj?.foo : obj?.foo)();
// but not test expression
// (obj?.foo ? a : b)();
if node.syntax() == expression.consequent().ok()?.syntax()
|| node.syntax() == expression.alternate().ok()?.syntax()
{
parent = expression.parent::<RuleNode>()
}
}
RuleNode::JsCallExpression(expression) => {
if expression.is_optional() {
// The current optional chain is inside another optional chain which will also be processed by the rule so we can skip current optional chain
// a?.b?.()
return None;
}
if is_inside_parenthesis {
// it means we've found a error because parentheses limit the scope
// (a?.b)()
return Some(expression.arguments().ok()?.syntax().text_trimmed_range());
}
// a()...
parent = expression.parent::<RuleNode>()
}
RuleNode::JsStaticMemberExpression(expression) => {
if expression.is_optional() {
// The current optional chain is inside another optional chain which will also be processed by the rule so we can skip current optional chain
// a?.b?.c
return None;
}
if is_inside_parenthesis {
// it means we've found a error because parentheses limit the scope
// (a?.b).c
return Some(expression.member().ok()?.syntax().text_trimmed_range());
}
// a.b....
parent = expression.parent::<RuleNode>()
}
RuleNode::JsComputedMemberExpression(expression) => {
if expression.is_optional() {
// The current optional chain is inside another optional chain which will also be processed by the rule so we can skip current optional chain
// a?.[b]?.[c]
return None;
}
if is_inside_parenthesis {
// it means we've found a error because parentheses limit the scope
// (a?.[b]).c
return Some(TextRange::new(
expression
.l_brack_token()
.ok()?
.text_trimmed_range()
.start(),
expression.r_brack_token().ok()?.text_trimmed_range().end(),
));
}
// a[b]...
parent = expression.parent::<RuleNode>()
}
RuleNode::JsTemplateExpression(expression) => {
// a?.b``
// (a?.b)``
return Some(TextRange::new(
expression.l_tick_token().ok()?.text_trimmed_range().start(),
expression.r_tick_token().ok()?.text_trimmed_range().end(),
));
}
RuleNode::JsForOfStatement(statement) => {
if node.syntax() == statement.expression().ok()?.syntax() {
// we can have an error only if we have an optional chain in the expression node
// for (foo of obj?.bar);
return Some(statement.syntax().text_trimmed_range());
}
}
RuleNode::JsWithStatement(statement) => {
if node.syntax() == statement.object().ok()?.syntax() {
// we can have an error only if we have an optional chain in the object part
// with (obj?.foo) {};
return Some(statement.syntax().text_trimmed_range());
}
}
RuleNode::JsInitializerClause(initializer) => {
if let Some(parent) = initializer.parent::<JsVariableDeclarator>() {
if matches!(
parent.id(),
Ok(AnyJsBindingPattern::JsObjectBindingPattern(_)
| AnyJsBindingPattern::JsArrayBindingPattern(_),)
) {
return Some(parent.syntax().text_trimmed_range());
}
} else if let Some(parent) =
initializer.parent::<JsObjectAssignmentPatternProperty>()
{
if matches!(
parent.pattern(),
Ok(AnyJsAssignmentPattern::JsObjectAssignmentPattern(_)
| AnyJsAssignmentPattern::JsArrayAssignmentPattern(_),)
) {
// ({bar: [ foo ] = obj?.prop} = {});
return Some(parent.syntax().text_trimmed_range());
}
}
}
RuleNode::JsAssignmentExpression(expression) => {
if matches!(
expression.left(),
Ok(AnyJsAssignmentPattern::JsObjectAssignmentPattern(_)
| AnyJsAssignmentPattern::JsArrayAssignmentPattern(_),)
) {
return Some(expression.syntax().text_trimmed_range());
}
}
RuleNode::JsAssignmentWithDefault(assigment) => {
if matches!(
assigment.pattern(),
Ok(AnyJsAssignmentPattern::JsObjectAssignmentPattern(_)
| AnyJsAssignmentPattern::JsArrayAssignmentPattern(_))
) {
// [{ foo } = obj?.bar] = [];
return Some(assigment.syntax().text_trimmed_range());
}
}
RuleNode::JsSpread(spread) => {
// it's not an error to have a spread inside object
// { ...a?.b }
if spread.parent::<JsObjectMemberList>().is_none() {
return Some(spread.syntax().text_trimmed_range());
}
}
RuleNode::JsInExpression(expression) => {
if node.syntax() == expression.object().ok()?.syntax() {
// we can have an error only if we have an optional chain in the object part
// a in foo?.bar;
return Some(expression.syntax().text_trimmed_range());
}
}
RuleNode::JsInstanceofExpression(expression) => {
if node.syntax() == expression.right().ok()?.syntax() {
// we can have an error only if we have an optional chain in the right part
// foo instanceof obj?.prop;
return Some(expression.syntax().text_trimmed_range());
}
}
};
node = current_parent;
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, range: &Self::State) -> Option<RuleDiagnostic> {
let query_node = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
query_node.range(),
markup! {
"Unsafe usage of optional chaining."
},
)
.detail(
range,
"If it short-circuits with 'undefined' the evaluation will throw TypeError here:",
),
)
}
}
declare_node_union! {
pub(crate) QueryNode = JsCallExpression | JsStaticMemberExpression | JsComputedMemberExpression
}
impl QueryNode {
pub fn is_optional(&self) -> bool {
match self {
QueryNode::JsCallExpression(expression) => expression.is_optional(),
QueryNode::JsStaticMemberExpression(expression) => expression.is_optional(),
QueryNode::JsComputedMemberExpression(expression) => expression.is_optional(),
}
}
pub fn range(&self) -> Option<TextRange> {
let token = match self {
QueryNode::JsCallExpression(expression) => expression.optional_chain_token(),
QueryNode::JsStaticMemberExpression(expression) => expression.operator_token().ok(),
QueryNode::JsComputedMemberExpression(expression) => expression.optional_chain_token(),
};
Some(token?.text_trimmed_range())
}
}
impl From<QueryNode> for AnyJsExpression {
fn from(node: QueryNode) -> AnyJsExpression {
match node {
QueryNode::JsCallExpression(expression) => expression.into(),
QueryNode::JsStaticMemberExpression(expression) => expression.into(),
QueryNode::JsComputedMemberExpression(expression) => expression.into(),
}
}
}
impl From<QueryNode> for RuleNode {
fn from(node: QueryNode) -> RuleNode {
match node {
QueryNode::JsCallExpression(expression) => RuleNode::JsCallExpression(expression),
QueryNode::JsStaticMemberExpression(expression) => {
RuleNode::JsStaticMemberExpression(expression)
}
QueryNode::JsComputedMemberExpression(expression) => {
RuleNode::JsComputedMemberExpression(expression)
}
}
}
}
declare_node_union! {
/// Only these variants of the union can be part of an unsafe optional chain.
pub(crate) RuleNode =
JsLogicalExpression
| JsSequenceExpression
| JsConditionalExpression
| JsAwaitExpression
| JsParenthesizedExpression
| JsCallExpression
| JsNewExpression
| JsStaticMemberExpression
| JsComputedMemberExpression
| JsTemplateExpression
| JsForOfStatement
| JsWithStatement
| JsInitializerClause
| JsAssignmentExpression
| JsSpread
| JsExtendsClause
| JsInExpression
| JsInstanceofExpression
| JsAssignmentWithDefault
}
| 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/no_static_only_class.rs | crates/rome_js_analyze/src/analyzers/nursery/no_static_only_class.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{
AnyJsClass, AnyJsClassMember, JsGetterClassMember, JsMethodClassMember, JsPropertyClassMember,
JsSetterClassMember, TsGetterSignatureClassMember, TsIndexSignatureClassMember,
TsInitializedPropertySignatureClassMember, TsMethodSignatureClassMember,
TsPropertySignatureClassMember, TsSetterSignatureClassMember,
};
use rome_rowan::{AstNode, AstNodeList};
declare_rule! {
/// This rule reports when a class has no non-static members, such as for a class used exclusively as a static namespace.
///
/// Users who come from a [OOP](https://en.wikipedia.org/wiki/Object-oriented_programming) paradigm may wrap their utility functions in an extra class,
/// instead of putting them at the top level of an ECMAScript module. Doing so is generally unnecessary in JavaScript and TypeScript projects.
///
/// - Wrapper classes add extra cognitive complexity to code without adding any structural improvements
/// - Whatever would be put on them, such as utility functions, are already organized by virtue of being in a module.
/// - As an alternative, you can import * as ... the module to get all of them in a single object.
/// - IDEs can't provide as good suggestions for static class or namespace imported properties when you start typing property names
/// - It's more difficult to statically analyze code for unused variables, etc. when they're all on the class (see: Finding dead code (and dead types) in TypeScript).
///
/// Source: https://typescript-eslint.io/rules/no-extraneous-class
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// class X {
/// static foo = false;
/// static bar() {};
/// }
/// ```
/// ```js,expect_diagnostic
/// class StaticConstants {
/// static readonly version = 42;
///
/// static isProduction() {
/// return process.env.NODE_ENV === 'production';
/// }
/// }
/// ```
///
/// ## Valid
///
/// ```js
/// const X = {
/// foo: false,
/// bar() {}
/// };
/// ```
/// ```js
/// export const version = 42;
///
/// export function isProduction() {
/// return process.env.NODE_ENV === 'production';
/// }
///
/// function logHelloWorld() {
/// console.log('Hello, world!');
/// }
/// ```
/// ```js
/// class Empty {}
/// ```
///
/// ## Notes on Mutating Variables
/// One case you need to be careful of is exporting mutable variables. While class properties can be mutated externally, exported variables are always constant. This means that importers can only ever read the first value they are assigned and cannot write to the variables.
///
/// Needing to write to an exported variable is very rare and is generally considered a code smell. If you do need it you can accomplish it using getter and setter functions:
/// ```js,expect_diagnostic
/// export class Utilities {
/// static mutableCount = 1;
/// static incrementCount() {
/// Utilities.mutableCount += 1;
/// }
/// }
/// ```
///
/// Do this instead:
/// ```js
/// let mutableCount = 1;
///
/// export function getMutableCount() {
/// return mutableField;
/// }
///
/// export function incrementCount() {
/// mutableField += 1;
/// }
/// ```
pub(crate) NoStaticOnlyClass {
version: "next",
name: "noStaticOnlyClass",
recommended: true,
}
}
trait HasStaticModifier {
fn has_static_modifier(&self) -> bool;
}
macro_rules! impl_has_static_modifiers {
($type:ty) => {
impl HasStaticModifier for $type {
fn has_static_modifier(&self) -> bool {
self.modifiers()
.iter()
.any(|modifier| modifier.as_js_static_modifier().is_some())
}
}
};
}
impl_has_static_modifiers!(JsGetterClassMember);
impl_has_static_modifiers!(JsSetterClassMember);
impl_has_static_modifiers!(JsMethodClassMember);
impl_has_static_modifiers!(JsPropertyClassMember);
impl_has_static_modifiers!(TsGetterSignatureClassMember);
impl_has_static_modifiers!(TsIndexSignatureClassMember);
impl_has_static_modifiers!(TsInitializedPropertySignatureClassMember);
impl_has_static_modifiers!(TsMethodSignatureClassMember);
impl_has_static_modifiers!(TsPropertySignatureClassMember);
impl_has_static_modifiers!(TsSetterSignatureClassMember);
impl Rule for NoStaticOnlyClass {
type Query = Ast<AnyJsClass>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let class_declaration = ctx.query();
// If the class is empty, we can't be sure that the user can use a module-based approach instead
// Also, the user might be in the process of writing a class, so we won't warn them yet
if class_declaration.members().is_empty() {
return None;
}
// If the class has decorators, we can't be sure that the user can use a module-based approach instead
if !class_declaration.decorators().is_empty() {
return None;
}
let all_members_static = class_declaration
.members()
.iter()
.filter_map(|member| match member {
AnyJsClassMember::JsBogusMember(_) => None,
AnyJsClassMember::JsEmptyClassMember(_) => None,
AnyJsClassMember::JsConstructorClassMember(_) => Some(false), // See GH#4482: Constructors are not regarded as static
AnyJsClassMember::TsConstructorSignatureClassMember(_) => Some(false), // See GH#4482: Constructors are not regarded as static
AnyJsClassMember::JsGetterClassMember(m) => Some(m.has_static_modifier()),
AnyJsClassMember::JsMethodClassMember(m) => Some(m.has_static_modifier()),
AnyJsClassMember::JsPropertyClassMember(m) => Some(m.has_static_modifier()),
AnyJsClassMember::JsSetterClassMember(m) => Some(m.has_static_modifier()),
AnyJsClassMember::JsStaticInitializationBlockClassMember(_) => Some(true), // See GH#4482: Static initialization blocks are regarded as static
AnyJsClassMember::TsGetterSignatureClassMember(m) => Some(m.has_static_modifier()),
AnyJsClassMember::TsIndexSignatureClassMember(m) => Some(m.has_static_modifier()),
AnyJsClassMember::TsInitializedPropertySignatureClassMember(m) => {
Some(m.has_static_modifier())
}
AnyJsClassMember::TsMethodSignatureClassMember(m) => Some(m.has_static_modifier()),
AnyJsClassMember::TsPropertySignatureClassMember(m) => {
Some(m.has_static_modifier())
}
AnyJsClassMember::TsSetterSignatureClassMember(m) => Some(m.has_static_modifier()),
})
.all(|is_static| is_static);
if all_members_static {
Some(())
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let class_declaration = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
class_declaration.syntax().text_trimmed_range(),
markup! {
"Avoid classes that contain only static members."
},
)
.note(markup! {
"Prefer using simple functions instead of classes with only static members."
}),
)
}
}
| 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/no_nonoctal_decimal_escape.rs | crates/rome_js_analyze/src/analyzers/nursery/no_nonoctal_decimal_escape.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::JsStringLiteralExpression;
use rome_rowan::{AstNode, BatchMutationExt, TextRange};
use std::{collections::HashSet, ops::Range};
declare_rule! {
/// Disallow `\8` and `\9` escape sequences in string literals.
///
/// Since ECMAScript 2021, the escape sequences \8 and \9 have been defined as non-octal decimal escape sequences.
/// However, most JavaScript engines consider them to be "useless" escapes. For example:
///
/// ```js,ignore
/// "\8" === "8"; // true
/// "\9" === "9"; // true
/// ```
///
/// Although this syntax is deprecated, it is still supported for compatibility reasons.
/// If the ECMAScript host is not a web browser, this syntax is optional.
/// However, web browsers are still required to support it, but only in non-strict mode.
/// Regardless of your targeted environment, it is recommended to avoid using these escape sequences in new code.
///
/// Source: https://eslint.org/docs/latest/rules/no-nonoctal-decimal-escape
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const x = "\8";
/// ```
///
/// ```js,expect_diagnostic
/// const x = "Don't use \8 escape.";
/// ```
///
/// ```js,expect_diagnostic
/// const x = "Don't use \9 escape.";
/// ```
///
/// ## Valid
///
/// ```js
/// const x = "8";
/// ```
///
/// ```js
/// const x = "Don't use \\8 and \\9 escapes.";
/// ```
///
pub(crate) NoNonoctalDecimalEscape {
version: "next",
name: "noNonoctalDecimalEscape",
recommended: true,
}
}
#[derive(Debug)]
pub(crate) enum FixSuggestionKind {
Refactor,
}
#[derive(Debug)]
pub(crate) struct RuleState {
kind: FixSuggestionKind,
diagnostics_text_range: TextRange,
replace_from: String,
replace_to: String,
replace_string_range: Range<usize>,
}
impl Rule for NoNonoctalDecimalEscape {
type Query = Ast<JsStringLiteralExpression>;
type State = RuleState;
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let mut signals: Self::Signals = Vec::new();
let Some(token) = node.value_token().ok() else {
return signals
};
let text = token.text();
if !is_octal_escape_sequence(text) {
return signals;
}
let matches = lex_escape_sequences(text);
for EscapeSequence {
previous_escape,
decimal_escape,
decimal_escape_range: (decimal_escape_string_start, decimal_escape_string_end),
} in matches.iter()
{
let text_range_start = usize::from(node.range().start());
let decimal_escape_range_start = text_range_start + decimal_escape_string_start;
let decimal_escape_range_end = decimal_escape_range_start + decimal_escape.len();
let Some(decimal_escape_range) =
TextRange::try_from((decimal_escape_range_start, decimal_escape_range_end)).ok() else { continue };
let Some(decimal_char) = decimal_escape.chars().nth(1) else { continue };
let replace_string_range = *decimal_escape_string_start..*decimal_escape_string_end;
if let Some(previous_escape) = previous_escape {
if *previous_escape == "\\0" {
if let Some(unicode_escape) = get_unicode_escape('\0') {
let Some(previous_escape_range_start) = text.find(previous_escape) else { continue };
let Some(unicode_escape_text_range) = TextRange::try_from((
text_range_start + previous_escape_range_start,
decimal_escape_range_end
)).ok() else { continue };
let replace_string_range =
previous_escape_range_start..*decimal_escape_string_end;
// \0\8 -> \u00008
signals.push(RuleState {
kind: FixSuggestionKind::Refactor,
diagnostics_text_range: unicode_escape_text_range,
replace_from: format!("{previous_escape}{decimal_escape}"),
replace_to: format!("{unicode_escape}{decimal_char}"),
replace_string_range,
});
}
let Some(decimal_char_unicode_escaped) = get_unicode_escape(decimal_char) else { continue };
// \8 -> \u0038
signals.push(RuleState {
kind: FixSuggestionKind::Refactor,
diagnostics_text_range: decimal_escape_range,
replace_from: decimal_escape.to_string(),
replace_to: decimal_char_unicode_escaped,
replace_string_range: replace_string_range.clone(),
});
} else {
// \8 -> 8
signals.push(RuleState {
kind: FixSuggestionKind::Refactor,
diagnostics_text_range: decimal_escape_range,
replace_from: decimal_escape.to_string(),
replace_to: decimal_char.to_string(),
replace_string_range: replace_string_range.clone(),
})
}
}
}
let mut seen = HashSet::new();
signals.retain(|rule_state| seen.insert(rule_state.diagnostics_text_range));
signals
}
fn diagnostic(
_: &RuleContext<Self>,
RuleState {
diagnostics_text_range,
..
}: &Self::State,
) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
diagnostics_text_range,
markup! {
"Don't use "<Emphasis>"`\\8`"</Emphasis>" and "<Emphasis>"`\\9`"</Emphasis>" escape sequences in string literals."
},
).note(
markup! {
"The nonoctal decimal escape is a deprecated syntax that is left for compatibility and should not be used."
}
))
}
fn action(
ctx: &RuleContext<Self>,
RuleState {
kind,
replace_from,
replace_to,
replace_string_range,
..
}: &Self::State,
) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
let node = ctx.query();
let prev_token = node.value_token().ok()?;
let replaced = safe_replace_by_range(
prev_token.text().to_string(),
replace_string_range.to_owned(),
replace_to,
)?;
let next_token = make::ident(&replaced);
mutation.replace_token(prev_token, next_token);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: match kind {
FixSuggestionKind::Refactor => {
markup! ("Replace "<Emphasis>{replace_from}</Emphasis>" with "<Emphasis>{replace_to}</Emphasis>". This maintains the current functionality.").to_owned()
}
},
mutation,
})
}
}
fn safe_replace_by_range(
mut target: String,
range: Range<usize>,
replace_with: &str,
) -> Option<String> {
debug_assert!(target.len() >= range.end, "Range out of bounds");
debug_assert!(
target.is_char_boundary(range.start) && target.is_char_boundary(range.end),
"Range does not fall on char boundary"
);
target.replace_range(range, replace_with);
Some(target)
}
/// Returns true if input is octal decimal escape sequence and is not in JavaScript regular expression
fn is_octal_escape_sequence(input: &str) -> bool {
let mut in_regex = false;
let mut prev_char_was_escape = false;
for ch in input.chars() {
match ch {
'/' if !prev_char_was_escape => in_regex = !in_regex,
'8' | '9' if prev_char_was_escape && !in_regex => return true,
'\\' => prev_char_was_escape = !prev_char_was_escape,
_ => prev_char_was_escape = false,
}
}
false
}
#[derive(Debug, PartialEq)]
struct EscapeSequence {
previous_escape: Option<String>,
decimal_escape: String,
/// The range of the decimal escape sequence in the string literal
decimal_escape_range: (usize, usize),
}
/// Returns a list of escape sequences in the given string literal
fn lex_escape_sequences(input: &str) -> Vec<EscapeSequence> {
let mut result = Vec::new();
let mut previous_escape = None;
let mut decimal_escape_start = None;
let mut chars = input.char_indices().peekable();
while let Some((i, ch)) = chars.next() {
match ch {
'\\' => match chars.peek() {
Some((_, '0')) => {
previous_escape = Some("\\0".to_string());
// Consume '0'
let _ = chars.next();
}
Some((_, '8'..='9')) => {
decimal_escape_start = Some(i);
}
_ => (),
},
'8' | '9' if decimal_escape_start.is_some() => {
result.push(EscapeSequence {
previous_escape: previous_escape.take(),
decimal_escape: match ch {
'8' => "\\8".to_string(),
'9' => "\\9".to_string(),
_ => unreachable!(),
},
decimal_escape_range: (decimal_escape_start.unwrap(), i + ch.len_utf8()),
});
decimal_escape_start = None;
}
_ => previous_escape = Some(ch.to_string()),
}
}
result
}
/// Returns unicode escape sequence "\uXXXX" that represents the given character
pub(crate) fn get_unicode_escape(ch: char) -> Option<String> {
Some(format!("\\u{:04x}", ch as u32))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_octal_escape_sequence() {
assert!(!is_octal_escape_sequence(""));
assert!(!is_octal_escape_sequence("Hello World!"));
assert!(!is_octal_escape_sequence("\\0"));
assert!(!is_octal_escape_sequence("\\7"));
assert!(is_octal_escape_sequence("\\8"));
assert!(is_octal_escape_sequence("\\9"));
assert!(!is_octal_escape_sequence("/\\8/"));
assert!(!is_octal_escape_sequence("/\\9/"));
assert!(is_octal_escape_sequence("\\0\\8"));
assert!(is_octal_escape_sequence("\\7\\9"));
}
#[test]
fn test_get_unicode_escape() {
assert_eq!(get_unicode_escape('\0'), Some("\\u0000".to_string()));
assert_eq!(get_unicode_escape('a'), Some("\\u0061".to_string()));
assert_eq!(get_unicode_escape('👍'), Some("\\u1f44d".to_string()));
}
#[test]
fn test_parse_escape_sequences() {
assert_eq!(
lex_escape_sequences("test\\8\\9"),
vec![
EscapeSequence {
previous_escape: Some("t".to_string()),
decimal_escape: "\\8".to_string(),
decimal_escape_range: (4, 6)
},
EscapeSequence {
previous_escape: None,
decimal_escape: "\\9".to_string(),
decimal_escape_range: (6, 8)
}
]
);
assert_eq!(
lex_escape_sequences("\\0\\8"),
vec![EscapeSequence {
previous_escape: Some("\\0".to_string()),
decimal_escape: "\\8".to_string(),
decimal_escape_range: (2, 4)
},]
);
assert_eq!(
lex_escape_sequences("👍\\8\\9"),
vec![
EscapeSequence {
previous_escape: Some("👍".to_string()),
decimal_escape: "\\8".to_string(),
decimal_escape_range: (4, 6)
},
EscapeSequence {
previous_escape: None,
decimal_escape: "\\9".to_string(),
decimal_escape_range: (6, 8)
}
]
);
assert_eq!(
lex_escape_sequences("\\\\ \\8"),
vec![EscapeSequence {
previous_escape: Some(" ".to_string()),
decimal_escape: "\\8".to_string(),
decimal_escape_range: (3, 5)
},]
)
}
}
| 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/use_grouped_type_import.rs | crates/rome_js_analyze/src/analyzers/nursery/use_grouped_type_import.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::{
AnyJsNamedImport, AnyJsNamedImportSpecifier, JsImportNamedClause, TriviaPieceKind, T,
};
use rome_rowan::{AstNode, AstSeparatedList, BatchMutationExt};
declare_rule! {
/// Enforce the use of `import type` when an `import` only has specifiers with `type` qualifier.
///
/// The [`--verbatimModuleSyntax`](https://www.typescriptlang.org/tsconfig#verbatimModuleSyntax) _TypeScript_'s compiler option causes _TypeScript_ to do simple and predictable transpilation on `import` declarations.
/// Namely, it completely removes `import type` and any imported names with the `type` qualifier.
///
/// For instance, the following code:
///
/// ```ts,expect_diagnostic
/// import { type A, type B } from "mod-1";
/// import type { C, D } from "mod-2";
/// ```
///
/// is transpiled to:
///
/// ```ts
/// import "mod-1";
/// ```
///
/// Note that, an `import` that includes only names qualified with `type` is transpiled to a [side-effect `import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#import_a_module_for_its_side_effects_only).
/// This can be a surprising behavior: most of developers could expect the deletion of the `import`.
///
/// This behavior may still be desirable for applying the potential side-effects of the imported module.
/// In most cases you will not want to leave behind an unnecessary side effect `import`.
/// In teh remaining cases, it is often preferable to explicitly use a side-effect `import` to apply the side-effects of a module:
///
/// ```ts
/// import "mod"; // side-effect import
/// import type { A, B } from "mod";
/// ```
///
/// Source: https://typescript-eslint.io/rules/no-import-type-side-effects/
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// import { type A } from "mod";
/// ```
///
/// ## Valid
///
/// ```ts
/// import type { A, B } from "mod";
/// ```
///
/// ```ts
/// import { A, type B } from "mod";
/// ```
pub(crate) UseGroupedTypeImport {
version: "12.1.0",
name: "useGroupedTypeImport",
recommended: true,
}
}
impl Rule for UseGroupedTypeImport {
type Query = Ast<JsImportNamedClause>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if node.type_token().is_some() || node.default_specifier().is_some() {
return None;
}
if node
.named_import()
.ok()?
.as_js_named_import_specifiers()?
.specifiers()
.is_empty()
{
// import {} from ...
return None;
}
node.named_import()
.ok()?
.as_js_named_import_specifiers()?
.specifiers()
.iter()
.all(|specifier| {
let Ok(specifier) = specifier else { return false };
match specifier {
AnyJsNamedImportSpecifier::JsBogusNamedImportSpecifier(_) => false,
AnyJsNamedImportSpecifier::JsNamedImportSpecifier(specifier) => {
specifier.type_token().is_some()
}
AnyJsNamedImportSpecifier::JsShorthandNamedImportSpecifier(specifier) => {
specifier.type_token().is_some()
}
}
})
.then_some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
node.named_import().ok()?.range(),
markup! {
"The "<Emphasis>"type"</Emphasis>" qualifier can be moved just after "<Emphasis>"import"</Emphasis>" to completely remove the "<Emphasis>"import"</Emphasis>" at compile time."
},
)
.note(markup! {
"Only "<Emphasis>"import type"</Emphasis>" are removed at compile time."
}),
)
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let named_import = node.named_import().ok()?;
let named_import_specifiers = named_import.as_js_named_import_specifiers()?;
let named_import_specifiers_list = named_import_specifiers.specifiers();
let new_named_import_specifiers_list = make::js_named_import_specifier_list(
named_import_specifiers_list
.iter()
.filter_map(|specifier| specifier.ok())
.map(|specifier| match specifier {
AnyJsNamedImportSpecifier::JsNamedImportSpecifier(specifier) => {
AnyJsNamedImportSpecifier::JsNamedImportSpecifier(
specifier.with_type_token(None),
)
}
AnyJsNamedImportSpecifier::JsShorthandNamedImportSpecifier(specifier) => {
AnyJsNamedImportSpecifier::JsShorthandNamedImportSpecifier(
specifier.with_type_token(None),
)
}
specifier => specifier,
})
.collect::<Vec<_>>(),
named_import_specifiers_list
.separators()
.filter_map(|separator| separator.ok())
.collect::<Vec<_>>(),
);
let new_node = node
.clone()
.with_type_token(Some(
make::token(T![type]).with_trailing_trivia([(TriviaPieceKind::Whitespace, " ")]),
))
.with_named_import(AnyJsNamedImport::JsNamedImportSpecifiers(
named_import_specifiers
.clone()
.with_specifiers(new_named_import_specifiers_list),
));
mutation.replace_node(node.clone(), new_node);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Use "<Emphasis>"import type"</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/nursery/no_fallthrough_switch_clause.rs | crates/rome_js_analyze/src/analyzers/nursery/no_fallthrough_switch_clause.rs | use rome_rowan::{AstNode, AstNodeList};
use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{
AnyJsStatement, AnyJsSwitchClause, JsBlockStatement, JsStatementList, JsSwitchStatement,
};
declare_rule! {
/// Disallow fallthrough of `switch` clauses.
///
/// Switch clauses in `switch` statements fall through by default.
/// This can lead to unexpected behavior when forgotten.
///
/// Source: https://eslint.org/docs/latest/rules/no-fallthrough
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// switch(bar) {
/// case 0:
/// a();
/// case 1:
/// b()
/// }
/// ```
///
/// ## Valid
///
/// ```js
/// switch(foo) {
/// case 1:
/// doSomething();
/// break;
/// case 2:
/// doSomething();
/// }
/// ```
///
pub(crate) NoFallthroughSwitchClause {
version: "next",
name: "noFallthroughSwitchClause",
recommended: false,
}
}
impl Rule for NoFallthroughSwitchClause {
type Query = Ast<JsSwitchStatement>;
type State = AnyJsSwitchClause;
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let query = ctx.query();
let mut signals: Self::Signals = Vec::new();
let mut cases = query.cases().into_iter().peekable();
while let Some(any_case) = cases.next() {
let is_last = cases.peek().is_none();
if is_last {
continue;
}
if case_fell(&any_case) {
signals.push(any_case);
}
}
signals
}
fn diagnostic(_: &RuleContext<Self>, reference: &Self::State) -> Option<RuleDiagnostic> {
Some(
RuleDiagnostic::new(
rule_category!(),
reference.syntax().text_trimmed_range(),
markup! {
"This case is falling through to the next case."
},
)
.note(markup! {
"Add a `break` or `return` statement to the end of this case to prevent fallthrough."
}),
)
}
}
fn case_fell(case: &AnyJsSwitchClause) -> bool {
let statements = case.consequent();
!has_fall_blocker_statement(&statements) && statements.iter().count() != 0
}
fn has_fall_blocker_statement(statements: &JsStatementList) -> bool {
for statement in statements.iter() {
if is_fall_blocker_statement(&statement) {
return true;
}
if let Some(block_statement) = JsBlockStatement::cast_ref(statement.syntax()) {
if has_fall_blocker_statement(&block_statement.statements()) {
return true;
}
}
}
false
}
fn is_fall_blocker_statement(statement: &AnyJsStatement) -> bool {
matches!(
statement,
AnyJsStatement::JsBreakStatement(_)
| AnyJsStatement::JsReturnStatement(_)
| AnyJsStatement::JsThrowStatement(_)
| AnyJsStatement::JsContinueStatement(_)
)
}
| 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/no_confusing_arrow.rs | crates/rome_js_analyze/src/analyzers/nursery/no_confusing_arrow.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::JsArrowFunctionExpression;
declare_rule! {
/// Disallow arrow functions where they could be confused with comparisons.
///
/// Arrow functions (`=>`) are similar in syntax to some comparison operators (`>`, `<`, `<=`, and `>=`).
/// This rule warns against using the arrow function syntax in places where it could be confused with a comparison operator.
///
/// Source: https://eslint.org/docs/latest/rules/no-confusing-arrow
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// var x = a => 1 ? 2 : 3;
/// ```
///
/// ## Valid
///
/// ```js
/// var x = (a) => 1 ? 2 : 3;
///
/// var x = a => (1 ? 2 : 3);
///
/// var x = (a) => (1 ? 2 : 3);
///
/// var x = a => { return 1 ? 2 : 3; };
///
/// var x = (a) => { return 1 ? 2 : 3; };
/// ```
///
pub(crate) NoConfusingArrow {
version: "12.1.0",
name: "noConfusingArrow",
recommended: false,
}
}
impl Rule for NoConfusingArrow {
type Query = Ast<JsArrowFunctionExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let arrow_fn = ctx.query();
if arrow_fn.parameters().ok()?.as_js_parameters().is_some() {
// Don't report arrow functions that enclose its parameters with parenthesis.
return None;
}
arrow_fn
.body()
.ok()?
.as_any_js_expression()?
.as_js_conditional_expression()
.is_some()
.then_some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
ctx.query().fat_arrow_token().ok()?.text_trimmed_range(),
markup! {
"Fat arrows can be confused with some comparison operators ("
<Emphasis>"<"</Emphasis>", "
<Emphasis>">"</Emphasis>", "
<Emphasis>"<="</Emphasis>", "
<Emphasis>">="</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/nursery/use_literal_enum_members.rs | crates/rome_js_analyze/src/analyzers/nursery/use_literal_enum_members.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{
AnyJsExpression, AnyJsLiteralExpression, AnyJsMemberExpression, JsUnaryOperator,
TsEnumDeclaration,
};
use rome_rowan::{AstNode, TextRange};
use rustc_hash::FxHashSet;
declare_rule! {
/// Require all enum members to be literal values.
///
/// Usually, an enum member is initialized with a literal number or a literal string.
/// However, _TypeScript_ allows the value of an enum member to be many different kinds of expressions.
/// Using a computed enum member is often error-prone and confusing.
/// This rule requires the initialization of enum members with constant expressions.
/// It allows numeric and bitwise expressions for supporting [enum flags](https://stackoverflow.com/questions/39359740/what-are-enum-flags-in-typescript/39359953#39359953).
/// It also allows referencing previous enum members.
///
/// Source: https://typescript-eslint.io/rules/prefer-literal-enum-member/
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// const x = 2;
/// enum Computed {
/// A,
/// B = x,
/// }
/// ```
///
/// ## Valid
///
/// ```ts
/// enum Direction {
/// Left,
/// Right,
/// }
/// ```
///
/// ```ts
/// enum Order {
/// Less = -1,
/// Equal = 0,
/// Greater = 1,
/// }
/// ```
///
/// ```ts
/// enum State {
/// Open = "Open",
/// Close = "Close",
/// }
/// ```
///
/// ```ts
/// enum FileAccess {
/// None = 0,
/// Read = 1,
/// Write = 1 << 1,
/// All = Read | Write
/// }
/// ```
pub(crate) UseLiteralEnumMembers {
version: "12.1.0",
name: "useLiteralEnumMembers",
recommended: true,
}
}
impl Rule for UseLiteralEnumMembers {
type Query = Ast<TsEnumDeclaration>;
type State = TextRange;
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let enum_declaration = ctx.query();
let mut result = Vec::new();
let mut enum_member_names = FxHashSet::default();
let Ok(enum_name) = enum_declaration.id() else {
return result;
};
let Some(enum_name) = enum_name.as_js_identifier_binding()
.and_then(|x| x.name_token().ok()) else {
return result;
};
let enum_name = enum_name.text_trimmed();
for enum_member in enum_declaration.members() {
let Ok(enum_member) = enum_member else {
continue;
};
// no initializer => sequentially assigned literal integer
if let Some(initializer) = enum_member.initializer() {
if let Ok(initializer) = initializer.expression() {
let range = initializer.range();
if !is_constant_enum_expression(initializer, enum_name, &enum_member_names) {
result.push(range);
}
}
};
if let Ok(name) = enum_member.name() {
if let Some(name) = name.name() {
enum_member_names.insert(name.to_string());
}
}
}
result
}
fn diagnostic(
_: &RuleContext<Self>,
initializer_range: &Self::State,
) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
initializer_range,
markup! {
"The enum member should be initialized with a literal value such as a number or a string."
},
))
}
}
/// Returns true if `expr` is a constant enum expression.
/// A constant enum expression can contain numbers, string literals, and reference to
/// one of the enum member of `enum_member_names` of the enum name `enum_name`.
/// These values can be combined thanks to numeric, bitwise, and concatenation operations.
fn is_constant_enum_expression(
expr: AnyJsExpression,
enum_name: &str,
enum_member_names: &FxHashSet<String>,
) -> bool {
(move || {
// stack that holds expressions to validate.
let mut stack = Vec::new();
stack.push(expr);
while let Some(expr) = stack.pop() {
match expr.omit_parentheses() {
AnyJsExpression::AnyJsLiteralExpression(expr) => {
if !matches!(
expr,
AnyJsLiteralExpression::JsNumberLiteralExpression(_)
| AnyJsLiteralExpression::JsStringLiteralExpression(_)
) {
return Some(false);
}
}
AnyJsExpression::JsTemplateExpression(expr) => {
if !expr.is_constant() {
return Some(false);
}
}
AnyJsExpression::JsUnaryExpression(expr) => {
if !matches!(
expr.operator(),
Ok(JsUnaryOperator::BitwiseNot
| JsUnaryOperator::Minus
| JsUnaryOperator::Plus)
) {
return Some(false);
}
stack.push(expr.argument().ok()?)
}
AnyJsExpression::JsBinaryExpression(expr) => {
if !expr.is_binary_operation() && !expr.is_numeric_operation() {
return Some(false);
}
stack.push(expr.left().ok()?);
stack.push(expr.right().ok()?);
}
AnyJsExpression::JsIdentifierExpression(expr) => {
// Allow reference to previous member name
let name = expr.name().ok()?;
if !enum_member_names.contains(name.value_token().ok()?.text_trimmed()) {
return Some(false);
}
}
AnyJsExpression::JsStaticMemberExpression(expr) => {
if !is_enum_member_reference(expr.into(), enum_name, enum_member_names) {
return Some(false);
}
}
AnyJsExpression::JsComputedMemberExpression(expr) => {
if !is_enum_member_reference(expr.into(), enum_name, enum_member_names) {
return Some(false);
}
}
_ => {
return Some(false);
}
}
}
Some(true)
})()
.unwrap_or_default()
}
// Return true if `expr` is a reference to one of the enum member `enum_member_names`
// of the enum named `enum_name`.
fn is_enum_member_reference(
expr: AnyJsMemberExpression,
enum_name: &str,
enum_member_names: &FxHashSet<String>,
) -> bool {
(move || {
// Allow reference to previous member name namespaced by the enum name
let object = expr.object().ok()?.omit_parentheses();
let object = object.as_js_reference_identifier()?;
Some(object.has_name(enum_name) && enum_member_names.contains(expr.member_name()?.text()))
})()
.unwrap_or_default()
}
| 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/no_self_assign.rs | crates/rome_js_analyze/src/analyzers/nursery/no_self_assign.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{
inner_string_text, AnyJsArrayAssignmentPatternElement, AnyJsArrayElement, AnyJsAssignment,
AnyJsAssignmentPattern, AnyJsExpression, AnyJsLiteralExpression, AnyJsName,
AnyJsObjectAssignmentPatternMember, AnyJsObjectMember, JsAssignmentExpression,
JsAssignmentOperator, JsCallExpression, JsComputedMemberAssignment, JsComputedMemberExpression,
JsIdentifierAssignment, JsLanguage, JsName, JsPrivateName, JsReferenceIdentifier,
JsStaticMemberAssignment, JsStaticMemberExpression, JsSyntaxToken,
};
use rome_rowan::{
declare_node_union, AstNode, AstSeparatedList, AstSeparatedListNodesIterator, SyntaxError,
SyntaxResult, TextRange,
};
use std::collections::VecDeque;
use std::iter::FusedIterator;
declare_rule! {
/// Disallow assignments where both sides are exactly the same.
///
/// Self assignments have no effect, so probably those are an error due to incomplete refactoring.
///
/// Source: https://eslint.org/docs/latest/rules/no-self-assign
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// a = a;
/// ```
///
/// ```js,expect_diagnostic
/// [a] = [a];
/// ```
///
/// ```js,expect_diagnostic
/// ({a: b} = {a: b});
/// ```
///
/// ```js,expect_diagnostic
/// a.b = a.b;
/// ```
///
/// ```js,expect_diagnostic
/// a[b] = a[b];
/// ```
///
/// ```js,expect_diagnostic
/// a[b].foo = a[b].foo;
/// ```
///
/// ```js,expect_diagnostic
/// a['b'].foo = a['b'].foo;
/// ```
///
/// ## Valid
///
/// ```js
/// a &= a;
/// var a = a;
/// let a = a;
/// const a = a;
/// [a, b] = [b, a];
/// ```
///
pub(crate) NoSelfAssign {
version: "12.0.0",
name: "noSelfAssign",
recommended: true,
}
}
impl Rule for NoSelfAssign {
type Query = Ast<JsAssignmentExpression>;
type State = IdentifiersLike;
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let left = node.left().ok();
let right = node.right().ok();
let operator = node.operator().ok();
let mut state = vec![];
if let Some(operator) = operator {
if matches!(
operator,
JsAssignmentOperator::Assign
| JsAssignmentOperator::LogicalAndAssign
| JsAssignmentOperator::LogicalOrAssign
| JsAssignmentOperator::NullishCoalescingAssign
) {
if let (Some(left), Some(right)) = (left, right) {
if let Ok(pair) = AnyAssignmentLike::try_from((left, right)) {
compare_assignment_like(pair, &mut state);
}
}
}
}
state
}
fn diagnostic(_: &RuleContext<Self>, identifier_like: &Self::State) -> Option<RuleDiagnostic> {
let name = identifier_like.name()?;
Some(
RuleDiagnostic::new(
rule_category!(),
identifier_like.right_range(),
markup! {
{{name.text_trimmed()}}" is assigned to itself."
},
)
.detail(
identifier_like.left_range(),
markup! {
"This is where is assigned."
},
),
)
}
}
/// It traverses an [AnyAssignmentLike] and tracks the identifiers that have the same name
fn compare_assignment_like(
any_assignment_like: AnyAssignmentLike,
incorrect_identifiers: &mut Vec<IdentifiersLike>,
) {
let same_identifiers = SameIdentifiers {
current_assignment_like: any_assignment_like,
assignment_queue: VecDeque::new(),
};
for identifier_like in same_identifiers {
if with_same_identifiers(&identifier_like).is_some() {
incorrect_identifiers.push(identifier_like);
}
}
}
/// Convenient type to iterate through all the identifiers that can be found
/// inside an assignment expression.
struct SameIdentifiers {
/// The current assignment-like that is being inspected
current_assignment_like: AnyAssignmentLike,
/// A queue of assignments-like that are inspected during the traversal.
///
/// The queue is used to "save" the current traversal when it's needed to start a new one.
///
/// These kind of cases happen, for example, when we have a code like
///
/// ```js
/// [ a, [b, c], d ]
/// ```
///
/// After `a`, we find a new assignment-like pattern that requires a new traversal, so we save the
/// current traversal in the queue and we start a new one. When the inner traversal is finished,
/// we resume the previous one.
assignment_queue: VecDeque<AnyAssignmentLike>,
}
impl SameIdentifiers {
/// Any assignment-like has a left arm and a right arm. Both arms needs to be "similar"
/// in order to be compared. If during the traversal part of each arm differ, they are then ignored
///
/// The iterator logic makes sure to return the next eligible assignment-like.
fn next_assignment_like(&mut self) -> Option<AnyAssignmentLike> {
let current_assignment_like = &mut self.current_assignment_like;
match current_assignment_like {
AnyAssignmentLike::Arrays { left, right } => {
let new_assignment_like = Self::next_array_assignment(left, right);
// In case we have nested array/object structures, we save the current
// pair and we restore it once this iterator is consumed
if let Some(new_assignment_like) = new_assignment_like.as_ref() {
if new_assignment_like.has_sub_structures() {
self.assignment_queue
.push_back(self.current_assignment_like.clone());
}
}
new_assignment_like
}
AnyAssignmentLike::Object { left, right } => {
let new_assignment_like = Self::next_object_assignment(left, right);
// In case we have nested array/object structures, we save the current
// pair and we restore it once this iterator is consumed
if let Some(new_assignment_like) = new_assignment_like.as_ref() {
if new_assignment_like.has_sub_structures() {
self.assignment_queue
.push_back(self.current_assignment_like.clone());
}
}
new_assignment_like
}
AnyAssignmentLike::StaticExpression { left, right } => {
Self::next_static_expression(left, right)
}
AnyAssignmentLike::None | AnyAssignmentLike::Identifiers { .. } => {
let new_assignment = self.current_assignment_like.clone();
self.current_assignment_like = AnyAssignmentLike::None;
Some(new_assignment)
}
}
}
/// Handles cases where the assignment is something like
/// ```js
/// [a] = [a]
/// ```
fn next_array_assignment(
left: &mut AstSeparatedListNodesIterator<JsLanguage, AnyJsArrayAssignmentPatternElement>,
right: &mut AstSeparatedListNodesIterator<JsLanguage, AnyJsArrayElement>,
) -> Option<AnyAssignmentLike> {
if let (Some(left_element), Some(right_element)) = (left.next(), right.next()) {
let left_element = left_element.ok()?;
let right_element = right_element.ok()?;
if let (
AnyJsArrayAssignmentPatternElement::AnyJsAssignmentPattern(left),
AnyJsArrayElement::AnyJsExpression(right),
) = (left_element, right_element)
{
let new_assignment_like = AnyAssignmentLike::try_from((left, right)).ok()?;
return Some(new_assignment_like);
}
}
Some(AnyAssignmentLike::None)
}
/// Computes the next assignment like.
///
/// It handles code like:
///
/// ```js
/// {a} = {b}
/// ```
fn next_object_assignment(
left: &mut AstSeparatedListNodesIterator<JsLanguage, AnyJsObjectAssignmentPatternMember>,
right: &mut AstSeparatedListNodesIterator<JsLanguage, AnyJsObjectMember>,
) -> Option<AnyAssignmentLike> {
let result = if let (Some(left_element), Some(right_element)) = (left.next(), right.next())
{
let left_element = left_element.ok()?;
let right_element = right_element.ok()?;
match (left_element, right_element) {
// matches {a} = {a}
(
AnyJsObjectAssignmentPatternMember::JsObjectAssignmentPatternShorthandProperty(
left,
),
AnyJsObjectMember::JsShorthandPropertyObjectMember(right),
) => AnyAssignmentLike::Identifiers(IdentifiersLike::IdentifierAndReference(
left.identifier().ok()?,
right.name().ok()?,
)),
(
AnyJsObjectAssignmentPatternMember::JsObjectAssignmentPatternProperty(left),
AnyJsObjectMember::JsPropertyObjectMember(right),
) => {
let left = left.pattern().ok()?;
let right = right.value().ok()?;
match (left, right) {
// matches {a: b} = {a: b}
(
AnyJsAssignmentPattern::AnyJsAssignment(
AnyJsAssignment::JsIdentifierAssignment(left),
),
AnyJsExpression::JsIdentifierExpression(right),
) => AnyAssignmentLike::Identifiers(
IdentifiersLike::IdentifierAndReference(left, right.name().ok()?),
),
// matches {a: [b]} = {a: [b]}
(
AnyJsAssignmentPattern::JsArrayAssignmentPattern(left),
AnyJsExpression::JsArrayExpression(right),
) => AnyAssignmentLike::Arrays {
left: left.elements().iter(),
right: right.elements().iter(),
},
// matches {a: {b}} = {a: {b}}
(
AnyJsAssignmentPattern::JsObjectAssignmentPattern(left),
AnyJsExpression::JsObjectExpression(right),
) => AnyAssignmentLike::Object {
left: left.properties().iter(),
right: right.members().iter(),
},
_ => AnyAssignmentLike::None,
}
}
_ => AnyAssignmentLike::None,
}
} else {
AnyAssignmentLike::None
};
Some(result)
}
/// Computes the next static expression.
///
/// It handles codes like:
///
/// ```js
/// a.b = a.b;
/// a[b] = a[b];
/// ```
fn next_static_expression(
left: &mut AnyJsAssignmentExpressionLikeIterator,
right: &mut AnyJsAssignmentExpressionLikeIterator,
) -> Option<AnyAssignmentLike> {
if let (Some(left_item), Some(right_item)) = (left.next(), right.next()) {
let (left_name, left_reference) = left_item;
let (right_name, right_reference) = right_item;
if let Ok(identifier_like) = IdentifiersLike::try_from((left_name, right_name)) {
if with_same_identifiers(&identifier_like).is_some() {
if let (Some(left_reference), Some(right_reference)) =
(left_reference, right_reference)
{
if with_same_identifiers(&IdentifiersLike::References(
left_reference,
right_reference,
))
.is_some()
{
let source_identifier = IdentifiersLike::try_from((
left.source_member.clone(),
right.source_member.clone(),
))
.ok()?;
return Some(AnyAssignmentLike::Identifiers(source_identifier));
}
} else {
return Self::next_static_expression(left, right);
}
}
}
}
Some(AnyAssignmentLike::None)
}
}
impl Iterator for SameIdentifiers {
type Item = IdentifiersLike;
fn next(&mut self) -> Option<Self::Item> {
if matches!(self.current_assignment_like, AnyAssignmentLike::None) {
return None;
}
loop {
let new_assignment_like = self.next_assignment_like()?;
match new_assignment_like {
// if we are here, it's plausible that we consumed the current iterator and we have to
// resume the previous one
AnyAssignmentLike::None => {
// we still have assignments-like to complete, so we continue the loop
if let Some(pair) = self.assignment_queue.pop_front() {
self.current_assignment_like = pair;
continue;
}
// the queue is empty
else {
return None;
}
}
AnyAssignmentLike::Identifiers(identifier_like) => {
return Some(identifier_like);
}
// we have a sub structure, which means we queue the current assignment,
// and inspect the sub structure
AnyAssignmentLike::StaticExpression { .. }
| AnyAssignmentLike::Object { .. }
| AnyAssignmentLike::Arrays { .. } => {
self.assignment_queue
.push_back(self.current_assignment_like.clone());
self.current_assignment_like = new_assignment_like;
continue;
}
}
}
}
}
impl FusedIterator for SameIdentifiers {}
/// A convenient iterator that continues to return the nested [JsStaticMemberExpression]
#[derive(Debug, Clone)]
struct AnyJsAssignmentExpressionLikeIterator {
source_member: AnyNameLike,
source_object: AnyJsExpression,
current_member_expression: Option<AnyAssignmentExpressionLike>,
drained: bool,
}
impl AnyJsAssignmentExpressionLikeIterator {
fn from_static_member_expression(source: JsStaticMemberExpression) -> SyntaxResult<Self> {
Ok(Self {
source_member: source.member().map(AnyNameLike::from)?,
source_object: source.object()?,
current_member_expression: None,
drained: false,
})
}
fn from_static_member_assignment(source: JsStaticMemberAssignment) -> SyntaxResult<Self> {
Ok(Self {
source_member: source.member().map(AnyNameLike::from)?,
source_object: source.object()?,
current_member_expression: None,
drained: false,
})
}
fn from_computed_member_assignment(source: JsComputedMemberAssignment) -> SyntaxResult<Self> {
Ok(Self {
source_member: source.member().and_then(|expression| match expression {
AnyJsExpression::JsIdentifierExpression(node) => {
Ok(AnyNameLike::from(node.name()?))
}
_ => Err(SyntaxError::MissingRequiredChild),
})?,
source_object: source.object()?,
current_member_expression: None,
drained: false,
})
}
fn from_computed_member_expression(source: JsComputedMemberExpression) -> SyntaxResult<Self> {
Ok(Self {
source_member: source.member().and_then(|expression| match expression {
AnyJsExpression::JsIdentifierExpression(node) => {
Ok(AnyNameLike::from(node.name()?))
}
_ => Err(SyntaxError::MissingRequiredChild),
})?,
source_object: source.object()?,
current_member_expression: None,
drained: false,
})
}
}
impl Iterator for AnyJsAssignmentExpressionLikeIterator {
type Item = (AnyNameLike, Option<JsReferenceIdentifier>);
fn next(&mut self) -> Option<Self::Item> {
if self.drained {
return None;
}
let (name, object) =
if let Some(current_member_expression) = self.current_member_expression.as_ref() {
(
current_member_expression.member()?,
current_member_expression.object()?,
)
} else {
(self.source_member.clone(), self.source_object.clone())
};
let reference = match object {
AnyJsExpression::JsStaticMemberExpression(expression) => {
self.current_member_expression =
Some(AnyAssignmentExpressionLike::from(expression));
None
}
AnyJsExpression::JsIdentifierExpression(identifier) => {
// the left side of the static member expression is an identifier, which means that we can't
// go any further and we should mark the iterator and drained
self.drained = true;
Some(identifier.name().ok()?)
}
AnyJsExpression::JsCallExpression(call_expression) => {
self.current_member_expression = Some(
AnyAssignmentExpressionLike::JsCallExpression(call_expression),
);
None
}
AnyJsExpression::JsComputedMemberExpression(computed_expression) => {
self.current_member_expression = Some(
AnyAssignmentExpressionLike::JsComputedMemberExpression(computed_expression),
);
None
}
_ => return None,
};
Some((name, reference))
}
}
impl FusedIterator for AnyJsAssignmentExpressionLikeIterator {}
/// Convenient type to map assignments that have similar arms
#[derive(Debug, Clone)]
enum AnyAssignmentLike {
/// No assignments. This variant is used to signal that there aren't any more assignments
/// to inspect
None,
/// To track identifiers that will be compared and check if they are the same.
Identifiers(IdentifiersLike),
/// To track array assignment-likes
/// ```js
/// [a] = [a]
/// ```
///
/// It stores a left iterator and a right iterator. Using iterators is useful to signal when
/// there aren't any more elements to inspect.
Arrays {
left: AstSeparatedListNodesIterator<JsLanguage, AnyJsArrayAssignmentPatternElement>,
right: AstSeparatedListNodesIterator<JsLanguage, AnyJsArrayElement>,
},
/// To track assignments like
/// ```js
/// {a} = {a}
/// ```
///
/// It stores a left iterator and a right iterator. Using iterators is useful to signal when
/// there aren't any more elements to inspect.
Object {
left: AstSeparatedListNodesIterator<JsLanguage, AnyJsObjectAssignmentPatternMember>,
right: AstSeparatedListNodesIterator<JsLanguage, AnyJsObjectMember>,
},
/// To track static expressions
/// ```js
/// a.b = a.b;
/// a[b] = a[b];
/// ```
///
/// It stores a left iterator and a right iterator. Using iterators is useful to signal when
/// there aren't any more elements to inspect.
StaticExpression {
left: AnyJsAssignmentExpressionLikeIterator,
right: AnyJsAssignmentExpressionLikeIterator,
},
}
declare_node_union! {
pub(crate) AnyNameLike = AnyJsName | JsReferenceIdentifier | AnyJsLiteralExpression
}
declare_node_union! {
pub(crate) AnyAssignmentExpressionLike = JsStaticMemberExpression | JsComputedMemberExpression | JsCallExpression
}
impl AnyAssignmentExpressionLike {
fn member(&self) -> Option<AnyNameLike> {
match self {
AnyAssignmentExpressionLike::JsStaticMemberExpression(node) => {
node.member().ok().map(AnyNameLike::from)
}
AnyAssignmentExpressionLike::JsComputedMemberExpression(node) => {
node.member().ok().and_then(|node| {
Some(match node {
AnyJsExpression::JsIdentifierExpression(node) => node.name().ok()?.into(),
AnyJsExpression::AnyJsLiteralExpression(node) => node.into(),
_ => return None,
})
})
}
AnyAssignmentExpressionLike::JsCallExpression(node) => node
.callee()
.ok()
.and_then(|callee| callee.as_js_static_member_expression().cloned())
.and_then(|callee| callee.member().ok())
.and_then(|member| {
let js_name = member.as_js_name()?;
Some(AnyNameLike::from(AnyJsName::JsName(js_name.clone())))
}),
}
}
fn object(&self) -> Option<AnyJsExpression> {
match self {
AnyAssignmentExpressionLike::JsStaticMemberExpression(node) => node.object().ok(),
AnyAssignmentExpressionLike::JsComputedMemberExpression(node) => node.object().ok(),
AnyAssignmentExpressionLike::JsCallExpression(node) => node
.callee()
.ok()?
.as_js_static_member_expression()?
.object()
.ok(),
}
}
}
impl AnyAssignmentLike {
const fn has_sub_structures(&self) -> bool {
matches!(
self,
AnyAssignmentLike::Arrays { .. } | AnyAssignmentLike::Object { .. }
)
}
}
impl TryFrom<(AnyJsAssignmentPattern, AnyJsExpression)> for AnyAssignmentLike {
type Error = SyntaxError;
fn try_from(
(left, right): (AnyJsAssignmentPattern, AnyJsExpression),
) -> Result<Self, Self::Error> {
Ok(match (left, right) {
(
AnyJsAssignmentPattern::JsArrayAssignmentPattern(left),
AnyJsExpression::JsArrayExpression(right),
) => AnyAssignmentLike::Arrays {
left: left.elements().iter(),
right: right.elements().iter(),
},
(
AnyJsAssignmentPattern::JsObjectAssignmentPattern(left),
AnyJsExpression::JsObjectExpression(right),
) => AnyAssignmentLike::Object {
left: left.properties().iter(),
right: right.members().iter(),
},
(
AnyJsAssignmentPattern::AnyJsAssignment(AnyJsAssignment::JsIdentifierAssignment(
left,
)),
AnyJsExpression::JsIdentifierExpression(right),
) => AnyAssignmentLike::Identifiers(IdentifiersLike::IdentifierAndReference(
left,
right.name()?,
)),
(
AnyJsAssignmentPattern::AnyJsAssignment(AnyJsAssignment::JsStaticMemberAssignment(
left,
)),
AnyJsExpression::JsStaticMemberExpression(right),
) => AnyAssignmentLike::StaticExpression {
left: AnyJsAssignmentExpressionLikeIterator::from_static_member_assignment(left)?,
right: AnyJsAssignmentExpressionLikeIterator::from_static_member_expression(right)?,
},
(
AnyJsAssignmentPattern::AnyJsAssignment(
AnyJsAssignment::JsComputedMemberAssignment(left),
),
AnyJsExpression::JsComputedMemberExpression(right),
) => AnyAssignmentLike::StaticExpression {
left: AnyJsAssignmentExpressionLikeIterator::from_computed_member_assignment(left)?,
right: AnyJsAssignmentExpressionLikeIterator::from_computed_member_expression(
right,
)?,
},
_ => AnyAssignmentLike::None,
})
}
}
/// Convenient type that pair possible combination of "identifiers" like that we can find.
///
/// Each variant has two types:
/// - the first one is the identifier found in the left arm of the assignment;
/// - the second one is the identifier found in the right arm of the assignment;
#[derive(Debug, Clone)]
pub(crate) enum IdentifiersLike {
/// To store identifiers found in code like:
///
/// ```js
/// a = a;
/// [a] = [a];
/// {a} = {a};
/// ```
IdentifierAndReference(JsIdentifierAssignment, JsReferenceIdentifier),
/// To store identifiers found in code like:
///
/// ```js
/// a[b] = a[b];
/// ```
References(JsReferenceIdentifier, JsReferenceIdentifier),
/// To store identifiers found in code like:
///
/// ```js
/// a.b = a.b;
/// ```
Name(JsName, JsName),
/// To store identifiers found in code like:
///
/// ```js
/// a.#b = a.#b;
/// ```
PrivateName(JsPrivateName, JsPrivateName),
/// To store identifiers found in code like:
///
/// ```js
/// a['b'].d = a['b'].d
/// a[3].d = a[4].d
/// ```
Literal(AnyJsLiteralExpression, AnyJsLiteralExpression),
}
impl TryFrom<(AnyNameLike, AnyNameLike)> for IdentifiersLike {
type Error = SyntaxError;
fn try_from((left, right): (AnyNameLike, AnyNameLike)) -> Result<Self, Self::Error> {
match (left, right) {
(
AnyNameLike::AnyJsName(AnyJsName::JsName(left)),
AnyNameLike::AnyJsName(AnyJsName::JsName(right)),
) => Ok(Self::Name(left, right)),
(
AnyNameLike::AnyJsName(AnyJsName::JsPrivateName(left)),
AnyNameLike::AnyJsName(AnyJsName::JsPrivateName(right)),
) => Ok(Self::PrivateName(left, right)),
(
AnyNameLike::JsReferenceIdentifier(left),
AnyNameLike::JsReferenceIdentifier(right),
) => Ok(Self::References(left, right)),
(
AnyNameLike::AnyJsLiteralExpression(left),
AnyNameLike::AnyJsLiteralExpression(right),
) => Ok(Self::Literal(left, right)),
_ => unreachable!("you should map the correct references"),
}
}
}
impl IdentifiersLike {
fn left_range(&self) -> TextRange {
match self {
IdentifiersLike::IdentifierAndReference(left, _) => left.range(),
IdentifiersLike::Name(left, _) => left.range(),
IdentifiersLike::PrivateName(left, _) => left.range(),
IdentifiersLike::References(left, _) => left.range(),
IdentifiersLike::Literal(left, _) => left.range(),
}
}
fn right_range(&self) -> TextRange {
match self {
IdentifiersLike::IdentifierAndReference(_, right) => right.range(),
IdentifiersLike::Name(_, right) => right.range(),
IdentifiersLike::PrivateName(_, right) => right.range(),
IdentifiersLike::References(_, right) => right.range(),
IdentifiersLike::Literal(_, right) => right.range(),
}
}
fn name(&self) -> Option<JsSyntaxToken> {
match self {
IdentifiersLike::IdentifierAndReference(_, right) => right.value_token().ok(),
IdentifiersLike::Name(_, right) => right.value_token().ok(),
IdentifiersLike::PrivateName(_, right) => right.value_token().ok(),
IdentifiersLike::References(_, right) => right.value_token().ok(),
IdentifiersLike::Literal(_, right) => right.value_token().ok(),
}
}
}
/// Checks if the left identifier and the right reference have the same name
fn with_same_identifiers(identifiers_like: &IdentifiersLike) -> Option<()> {
let (left_value, right_value) = match &identifiers_like {
IdentifiersLike::IdentifierAndReference(left, right) => {
let left_value = left.name_token().ok()?;
let right_value = right.value_token().ok()?;
(left_value, right_value)
}
IdentifiersLike::Name(left, right) => {
let left_value = left.value_token().ok()?;
let right_value = right.value_token().ok()?;
(left_value, right_value)
}
IdentifiersLike::PrivateName(left, right) => {
let left_value = left.value_token().ok()?;
let right_value = right.value_token().ok()?;
(left_value, right_value)
}
IdentifiersLike::References(left, right) => {
let left_value = left.value_token().ok()?;
let right_value = right.value_token().ok()?;
(left_value, right_value)
}
IdentifiersLike::Literal(left, right) => match (left, right) {
(
AnyJsLiteralExpression::JsStringLiteralExpression(left),
AnyJsLiteralExpression::JsStringLiteralExpression(right),
) => {
let left_value = left.value_token().ok()?;
let right_value = right.value_token().ok()?;
(left_value, right_value)
}
(
AnyJsLiteralExpression::JsNumberLiteralExpression(left),
AnyJsLiteralExpression::JsNumberLiteralExpression(right),
) => {
let left_value = left.value_token().ok()?;
let right_value = right.value_token().ok()?;
(left_value, right_value)
}
_ => return None,
},
};
if inner_string_text(&left_value) == inner_string_text(&right_value) {
Some(())
} 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/nursery/use_import_restrictions.rs | crates/rome_js_analyze/src/analyzers/nursery/use_import_restrictions.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::JsModuleSource;
use rome_rowan::{AstNode, TokenText};
const INDEX_BASENAMES: &[&str] = &["index", "mod"];
const SOURCE_EXTENSIONS: &[&str] = &["js", "ts", "cjs", "cts", "mjs", "mts", "jsx", "tsx"];
declare_rule! {
/// Disallows package private imports.
///
/// This rules enforces the following restrictions:
///
/// ## Package private visibility
///
/// All exported symbols, such as types, functions or other things that may be exported, are
/// considered to be "package private". This means that modules that reside in the same
/// directory, as well as submodules of those "sibling" modules, are allowed to import them,
/// while any other modules that are further away in the file system are restricted from
/// importing them. A symbol's visibility may be extended by re-exporting from an index file.
///
/// Notes:
///
/// * This rule only applies to relative imports. External dependencies are exempted.
/// * This rule only applies to imports for JavaScript and TypeScript files. Imports for
/// resources such as images or CSS files are exempted.
///
/// Source: https://github.com/uhyo/eslint-plugin-import-access
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// // Attempt to import from `foo.js` from outside its `sub` module.
/// import { fooPackageVariable } from "./sub/foo.js";
/// ```
/// ```js,expect_diagnostic
/// // Attempt to import from `bar.ts` from outside its `aunt` module.
/// import { barPackageVariable } from "../aunt/bar.ts";
/// ```
///
/// ```js,expect_diagnostic
/// // Assumed to resolve to a JS/TS file.
/// import { fooPackageVariable } from "./sub/foo";
/// ```
///
/// ```js,expect_diagnostic
/// // If the `sub/foo` module is inaccessible, so is its index file.
/// import { fooPackageVariable } from "./sub/foo/index.js";
/// ```
///
/// ### Valid
///
/// ```js
/// // Imports within the same module are always allowed.
/// import { fooPackageVariable } from "./foo.js";
///
/// // Resources (anything other than JS/TS files) are exempt.
/// import { barResource } from "../aunt/bar.png";
///
/// // A parent index file is accessible like other modules.
/// import { internal } from "../../index.js";
///
/// // If the `sub` module is accessible, so is its index file.
/// import { subPackageVariable } from "./sub/index.js";
///
/// // Library imports are exempt.
/// import useAsync from "react-use/lib/useAsync";
/// ```
///
pub(crate) UseImportRestrictions {
version: "next",
name: "useImportRestrictions",
recommended: false,
}
}
impl Rule for UseImportRestrictions {
type Query = Ast<JsModuleSource>;
type State = ImportRestrictionsState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let binding = ctx.query();
let Ok(path) = binding.inner_string_text() else {
return None;
};
get_restricted_import(&path)
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let ImportRestrictionsState { path, suggestion } = state;
let diagnostic = RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
markup! {
"Importing package private symbols is prohibited from outside the module directory."
},
)
.note(markup! {
"Please import from "<Emphasis>{suggestion}</Emphasis>" instead "
"(you may need to re-export the symbol(s) from "<Emphasis>{path}</Emphasis>")."
});
Some(diagnostic)
}
}
pub(crate) struct ImportRestrictionsState {
/// The path that is being restricted.
path: String,
/// Suggestion from which to import instead.
suggestion: String,
}
fn get_restricted_import(module_path: &TokenText) -> Option<ImportRestrictionsState> {
if !module_path.starts_with('.') {
return None;
}
let mut path_parts: Vec<_> = module_path.text().split('/').collect();
let mut index_filename = None;
if let Some(extension) = get_extension(&path_parts) {
if !SOURCE_EXTENSIONS.contains(&extension) {
return None; // Resource files are exempt.
}
if let Some(basename) = get_basename(&path_parts) {
if INDEX_BASENAMES.contains(&basename) {
// We pop the index file because it shouldn't count as a path,
// component, but we store the file name so we can add it to
// both the reported path and the suggestion.
index_filename = path_parts.last().cloned();
path_parts.pop();
}
}
}
let is_restricted = path_parts
.iter()
.filter(|&&part| part != "." && part != "..")
.count()
> 1;
if !is_restricted {
return None;
}
let mut suggestion_parts = path_parts[..path_parts.len() - 1].to_vec();
// Push the index file if it exists. This makes sure the reported path
// matches the import path exactly.
if let Some(index_filename) = index_filename {
path_parts.push(index_filename);
// Assumes the user probably wants to use an index file that has the
// same name as the original.
suggestion_parts.push(index_filename);
}
Some(ImportRestrictionsState {
path: path_parts.join("/"),
suggestion: suggestion_parts.join("/"),
})
}
fn get_basename<'a>(path_parts: &'_ [&'a str]) -> Option<&'a str> {
path_parts.last().map(|&part| match part.find('.') {
Some(dot_index) if dot_index > 0 && dot_index < part.len() - 1 => &part[..dot_index],
_ => part,
})
}
fn get_extension<'a>(path_parts: &'_ [&'a str]) -> Option<&'a str> {
path_parts.last().and_then(|part| match part.find('.') {
Some(dot_index) if dot_index > 0 && dot_index < part.len() - 1 => {
Some(&part[dot_index + 1..])
}
_ => 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/nursery/use_arrow_function.rs | crates/rome_js_analyze/src/analyzers/nursery/use_arrow_function.rs | use crate::JsRuleAction;
use rome_analyze::{
context::RuleContext, declare_rule, ActionCategory, AddVisitor, Phases, QueryMatch, Queryable,
Rule, RuleDiagnostic, ServiceBag, Visitor, VisitorContext,
};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsExpression, AnyJsFunctionBody, AnyJsStatement, JsConstructorClassMember, JsFunctionBody,
JsFunctionDeclaration, JsFunctionExportDefaultDeclaration, JsFunctionExpression,
JsGetterClassMember, JsGetterObjectMember, JsLanguage, JsMethodClassMember,
JsMethodObjectMember, JsModule, JsScript, JsSetterClassMember, JsSetterObjectMember,
JsStaticInitializationBlockClassMember, JsThisExpression, T,
};
use rome_rowan::{
declare_node_union, AstNode, AstNodeList, AstSeparatedList, BatchMutationExt, Language,
SyntaxNode, TextRange, TriviaPieceKind, WalkEvent,
};
declare_rule! {
/// Use arrow functions over function expressions.
///
/// An arrow function expression is a compact alternative to a regular function expression,
/// with an important distinction:
/// `this` is not bound to the arrow function. It inherits `this` from its parent scope.
///
/// This rule proposes turning all function expressions that are not generators (`function*`) and don't use `this` into arrow functions.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const z = function() {
/// return 0;
/// }
/// ```
///
/// ```js,expect_diagnostic
/// const delegatedFetch = async function(url) {
/// return await fetch(url);
/// }
/// ```
///
/// ## Valid
///
/// ```js
/// const f = function() {
/// return this.prop;
/// }
/// ```
///
/// Named function expressions are ignored:
///
/// ```js
/// const z = function z() {
/// return 0;
/// }
/// ```
///
/// Function expressions that declare the type of `this` are also ignored:
///
/// ```ts
/// const z = function(this: A): number {
/// return 0;
/// }
/// ```
pub(crate) UseArrowFunction {
version: "next",
name: "useArrowFunction",
recommended: true,
}
}
impl Rule for UseArrowFunction {
type Query = ActualThisScope;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let AnyThisScopeMetadata { scope, has_this } = ctx.query();
if *has_this {
return None;
}
let AnyThisScope::JsFunctionExpression(function_expression) = scope else {
return None;
};
if function_expression.star_token().is_some() || function_expression.id().is_some() {
// Ignore generators and function with a name.
return None;
}
let has_this_parameter =
function_expression
.parameters()
.ok()?
.items()
.iter()
.any(|param| {
param
.map(|param| param.as_ts_this_parameter().is_some())
.unwrap_or_default()
});
if has_this_parameter {
// Ignore functions that explicitly declare a `this` type.
return None;
}
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
Some(
RuleDiagnostic::new(
rule_category!(),
ctx.query().scope.range(),
markup! {
"This "<Emphasis>"function expression"</Emphasis>" can be turned into an "<Emphasis>"arrow function"</Emphasis>"."
},
)
.note(markup! {
<Emphasis>"Function expressions"</Emphasis>" that don't use "<Emphasis>"this"</Emphasis>" can be turned into "<Emphasis>"arrow functions"</Emphasis>"."
}),
)
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let AnyThisScopeMetadata { scope, .. } = ctx.query();
let AnyThisScope::JsFunctionExpression(function_expression) = scope else { return None };
let mut arrow_function_builder = make::js_arrow_function_expression(
function_expression.parameters().ok()?.into(),
make::token(T![=>]).with_trailing_trivia([(TriviaPieceKind::Whitespace, " ")]),
to_arrow_body(function_expression.body().ok()?),
);
if let Some(async_token) = function_expression.async_token() {
arrow_function_builder = arrow_function_builder.with_async_token(async_token);
}
if let Some(type_parameters) = function_expression.type_parameters() {
arrow_function_builder = arrow_function_builder.with_type_parameters(type_parameters);
}
if let Some(return_type_annotation) = function_expression.return_type_annotation() {
arrow_function_builder =
arrow_function_builder.with_return_type_annotation(return_type_annotation);
}
let mut mutation = ctx.root().begin();
mutation.replace_node(
AnyJsExpression::JsFunctionExpression(function_expression.clone()),
AnyJsExpression::JsArrowFunctionExpression(arrow_function_builder.build()),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! { "Use an "<Emphasis>"arrow function"</Emphasis>" instead." }
.to_owned(),
mutation,
})
}
}
declare_node_union! {
pub(crate) AnyThisScope =
JsConstructorClassMember
| JsFunctionExpression
| JsFunctionDeclaration
| JsFunctionExportDefaultDeclaration
| JsGetterClassMember
| JsGetterObjectMember
| JsMethodClassMember
| JsMethodObjectMember
| JsModule
| JsScript
| JsSetterClassMember
| JsSetterObjectMember
| JsStaticInitializationBlockClassMember
}
#[derive(Debug, Clone)]
pub(crate) struct AnyThisScopeMetadata {
scope: AnyThisScope,
has_this: bool,
}
pub(crate) struct ActualThisScope(AnyThisScopeMetadata);
impl QueryMatch for ActualThisScope {
fn text_range(&self) -> TextRange {
self.0.scope.range()
}
}
impl Queryable for ActualThisScope {
type Input = Self;
type Language = JsLanguage;
type Output = AnyThisScopeMetadata;
type Services = ();
fn build_visitor(
analyzer: &mut impl AddVisitor<Self::Language>,
_: &<Self::Language as Language>::Root,
) {
analyzer.add_visitor(Phases::Syntax, AnyThisScopeVisitor::default);
}
fn unwrap_match(_: &ServiceBag, query: &Self::Input) -> Self::Output {
query.0.clone()
}
}
#[derive(Default)]
struct AnyThisScopeVisitor {
/// Vector to hold a function or block where `this` is scoped.
/// The function or block is associated to a boolean indicating whether it contains `this`.
stack: Vec<AnyThisScopeMetadata>,
}
impl Visitor for AnyThisScopeVisitor {
type Language = JsLanguage;
fn visit(
&mut self,
event: &WalkEvent<SyntaxNode<Self::Language>>,
mut ctx: VisitorContext<Self::Language>,
) {
match event {
WalkEvent::Enter(node) => {
// When the visitor enters a function node, push a new entry on the stack
if let Some(scope) = AnyThisScope::cast_ref(node) {
self.stack.push(AnyThisScopeMetadata {
scope,
has_this: false,
});
}
if JsThisExpression::can_cast(node.kind()) {
// When the visitor enters a `this` expression, set the
// `has_this` flag for the top entry on the stack to `true`
if let Some(AnyThisScopeMetadata { has_this, .. }) = self.stack.last_mut() {
*has_this = true;
}
}
}
WalkEvent::Leave(node) => {
if let Some(exit_scope) = AnyThisScope::cast_ref(node) {
if let Some(scope_metadata) = self.stack.pop() {
if scope_metadata.scope == exit_scope {
ctx.match_query(ActualThisScope(scope_metadata));
}
}
}
}
}
}
}
/// Get a minimal arrow function body from a regular function body.
fn to_arrow_body(body: JsFunctionBody) -> AnyJsFunctionBody {
let body_statements = body.statements();
// () => { ... }
let mut result = AnyJsFunctionBody::from(body);
let Some(AnyJsStatement::JsReturnStatement(return_statement)) = body_statements.iter().next() else {
return result;
};
let Some(return_arg) = return_statement.argument() else { return result; };
if body_statements.syntax().has_comments_direct()
|| return_statement.syntax().has_comments_direct()
|| return_arg.syntax().has_comments_direct()
{
// To keep comments, we keep the regular function body
return result;
}
// () => expression
result = AnyJsFunctionBody::AnyJsExpression(return_arg.clone());
let Some(first_token) = return_arg.syntax().first_token() else {
return result;
};
if first_token.kind() == T!['{'] {
// () => ({ ... })
result = AnyJsFunctionBody::AnyJsExpression(
make::js_parenthesized_expression(
make::token(T!['(']),
return_arg,
make::token(T![')']),
)
.into(),
);
}
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/nursery/no_void.rs | crates/rome_js_analyze/src/analyzers/nursery/no_void.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::JsUnaryExpression;
use rome_rowan::AstNode;
declare_rule! {
/// Disallow the use of `void` operators, which is not a familiar operator.
///
/// > The `void` operator is often used merely to obtain the undefined primitive value,
/// > usually using `void(0)` (which is equivalent to `void 0`). In these cases, the global variable `undefined` can be used.
///
/// Source: https://eslint.org/docs/latest/rules/no-void
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// void 0;
/// ```
///
pub(crate) NoVoid {
version: "next",
name: "noVoid",
recommended: false,
}
}
impl Rule for NoVoid {
type Query = Ast<JsUnaryExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let expression = ctx.query();
if expression.is_void().ok()? {
Some(())
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"The use of "<Emphasis>"void"</Emphasis>" is not allowed."
},
).note(
markup!{
"If you use "<Emphasis>"void"</Emphasis>" to alter the return type of a function or return `undefined`, use the global `undefined` instead."
}
))
}
}
| 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/no_excessive_complexity.rs | crates/rome_js_analyze/src/analyzers/nursery/no_excessive_complexity.rs | use bpaf::Bpaf;
use rome_analyze::{
context::RuleContext, declare_rule, AddVisitor, Phases, QueryMatch, Queryable, Rule,
RuleDiagnostic, ServiceBag, Visitor, VisitorContext,
};
use rome_console::markup;
use rome_deserialize::{
json::{has_only_known_keys, VisitJsonNode},
DeserializationDiagnostic, VisitNode,
};
use rome_js_syntax::{
AnyFunctionLike, JsBreakStatement, JsContinueStatement, JsElseClause, JsLanguage,
JsLogicalExpression, JsLogicalOperator,
};
use rome_json_syntax::{JsonLanguage, JsonSyntaxNode};
use rome_rowan::{AstNode, Language, SyntaxNode, TextRange, WalkEvent};
use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[cfg(feature = "schemars")]
use schemars::JsonSchema;
const MAX_FUNCTION_DEPTH: usize = 10;
const MAX_SCORE: u8 = u8::MAX;
declare_rule! {
/// Disallow functions that exceed a given complexity score.
///
/// The more complexity a function contains, the harder it is to understand
/// later on.
///
/// Reducing complexity helps to make code more maintenable, both by making
/// it easier to understand as well as by reducing chances of accidental
/// side-effects when making changes.
///
/// This rule calculates a complexity score for every function and disallows
/// those that exceed a configured complexity threshold (default: 10).
///
/// Source:
///
/// * https://github.com/SonarSource/eslint-plugin-sonarjs/blob/HEAD/docs/rules/cognitive-complexity.md
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// function tooComplex() {
/// for (let x = 0; x < 10; x++) {
/// for (let y = 0; y < 10; y++) {
/// if (x % 2 === 0) {
/// if (y % 2 === 0) {
/// console.log(x > y ? `${x} > ${y}` : `${y} > ${x}`);
/// }
/// }
/// }
/// }
/// }
/// ```
///
/// ## Options
///
/// Allows to specify the maximum allowed complexity.
///
/// ```json
/// {
/// "//": "...",
/// "options": {
/// "maxAllowedComplexity": 15
/// }
/// }
/// ```
///
/// The allowed values range from 1 through 254. The default is 10.
///
pub(crate) NoExcessiveComplexity {
version: "next",
name: "noExcessiveComplexity",
recommended: false,
}
}
impl Rule for NoExcessiveComplexity {
type Query = CognitiveComplexity;
type State = ();
type Signals = Option<Self::State>;
type Options = ComplexityOptions;
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let calculated_score = ctx.query().score.calculated_score;
(calculated_score > ctx.options().max_allowed_complexity).then_some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let CognitiveComplexity {
function_like,
score: ComplexityScore { calculated_score },
} = ctx.query();
let ComplexityOptions {
max_allowed_complexity,
} = ctx.options();
let range = function_like
.name_range()
.or_else(|| {
function_like
.function_token()
.map(|token| token.text_range())
})
.or_else(|| {
function_like
.fat_arrow_token()
.map(|token| token.text_range())
})
.or_else(|| function_like.body().ok().map(|body| body.range()))?;
Some(
RuleDiagnostic::new(
rule_category!(),
range,
markup!("Excessive complexity detected."),
)
.note(if calculated_score == &MAX_SCORE {
"Please refactor this function to reduce its complexity. \
It's currently too complex or too deeply nested to calculate an accurate score."
.to_owned()
} else {
format!(
"Please refactor this function to reduce its complexity score from \
{calculated_score} to the max allowed complexity {max_allowed_complexity}."
)
}),
)
}
}
#[derive(Clone)]
pub(crate) struct CognitiveComplexity {
function_like: AnyFunctionLike,
score: ComplexityScore,
}
impl QueryMatch for CognitiveComplexity {
fn text_range(&self) -> TextRange {
self.function_like.range()
}
}
impl Queryable for CognitiveComplexity {
type Input = Self;
type Language = JsLanguage;
type Output = Self;
type Services = ();
fn build_visitor(
analyzer: &mut impl AddVisitor<Self::Language>,
_: &<Self::Language as Language>::Root,
) {
analyzer.add_visitor(Phases::Syntax, CognitiveComplexityVisitor::default);
}
fn unwrap_match(_: &ServiceBag, query: &Self::Input) -> Self::Output {
query.clone()
}
}
struct CognitiveComplexityFunctionState {
function_like: AnyFunctionLike,
score: u8,
nesting_level: u8,
/// Cognitive complexity does not increase for every logical operator,
/// but for every *sequence* of identical logical operators. Therefore, we
/// track which operator was last seen and incur a penalty when a different
/// operator is encountered.
last_seen_operator: Option<JsLogicalOperator>,
}
#[derive(Default)]
struct CognitiveComplexityVisitor {
stack: Vec<CognitiveComplexityFunctionState>,
}
impl Visitor for CognitiveComplexityVisitor {
type Language = JsLanguage;
fn visit(
&mut self,
event: &WalkEvent<SyntaxNode<Self::Language>>,
ctx: VisitorContext<Self::Language>,
) {
match event {
WalkEvent::Enter(node) => self.on_enter(node),
WalkEvent::Leave(node) => self.on_leave(node, ctx),
}
}
}
impl CognitiveComplexityVisitor {
fn on_enter(&mut self, node: &SyntaxNode<JsLanguage>) {
let parent = self.stack.last();
if parent
.map(|parent| parent.score == MAX_SCORE)
.unwrap_or_default()
{
return; // No need for further processing if we're already at the max.
}
// When the visitor enters a function node, push a new entry on the stack
if let Some(function_like) = AnyFunctionLike::cast_ref(node) {
if self.stack.len() < MAX_FUNCTION_DEPTH {
self.stack.push(CognitiveComplexityFunctionState {
function_like,
score: 0,
nesting_level: parent
.map(|parent| parent.nesting_level + 1)
.unwrap_or_default(),
last_seen_operator: None,
});
} else if let Some(parent) = self.stack.last_mut() {
// Just mark the parent as being too complex. It already had a
// crazy level of nesting, so there's no point in reporting even
// deeper nested functions individually.
parent.score = MAX_SCORE;
}
}
if let Some(state) = self.stack.last_mut() {
if receives_structural_penalty(node) {
state.score = state.score.saturating_add(1);
if receives_nesting_penalty(node) {
state.score = state.score.saturating_add(state.nesting_level);
}
}
if increases_nesting(node) {
state.last_seen_operator = None;
state.nesting_level = state.nesting_level.saturating_add(1);
} else if let Some(operator) = JsLogicalExpression::cast_ref(node)
.and_then(|expression| expression.operator().ok())
{
if state.last_seen_operator != Some(operator) {
state.score = state.score.saturating_add(1);
state.last_seen_operator = Some(operator);
}
} else if let Some(alternate) =
JsElseClause::cast_ref(node).and_then(|js_else| js_else.alternate().ok())
{
if alternate.as_js_if_statement().is_some() {
// Prevent double nesting inside else-if.
state.nesting_level = state.nesting_level.saturating_sub(1);
} else {
state.score = state.score.saturating_add(1);
}
} else {
// Reset the operator for every other type of node.
state.last_seen_operator = None;
}
}
}
fn on_leave(&mut self, node: &SyntaxNode<JsLanguage>, mut ctx: VisitorContext<JsLanguage>) {
if let Some(exit_node) = AnyFunctionLike::cast_ref(node) {
if let Some(function_state) = self.stack.pop() {
if function_state.function_like == exit_node {
ctx.match_query(CognitiveComplexity {
function_like: exit_node,
score: ComplexityScore {
calculated_score: function_state.score,
},
});
} else {
// Push it back. This really should only be necessary
// if the max complexity or max nesting level was reached.
self.stack.push(function_state);
}
}
} else if let Some(state) = self.stack.last_mut() {
if state.score < MAX_SCORE {
if increases_nesting(node) {
state.nesting_level = state.nesting_level.saturating_sub(1);
} else if let Some(alternate) =
JsElseClause::cast_ref(node).and_then(|js_else| js_else.alternate().ok())
{
state.nesting_level = if alternate.as_js_if_statement().is_some() {
// Prevent double nesting inside else-if.
state.nesting_level.saturating_add(1)
} else {
state.nesting_level.saturating_sub(1)
};
}
}
}
}
}
/// Returns whether the node is considered to increase the nesting level inside
/// the function.
///
/// Note: These are mostly nodes that increase the complexity of the function's
/// control flow.
fn increases_nesting(node: &SyntaxNode<JsLanguage>) -> bool {
use rome_js_syntax::JsSyntaxKind::*;
is_loop_node(node)
|| matches!(
node.kind(),
JS_CATCH_CLAUSE | JS_CONDITIONAL_EXPRESSION | JS_IF_STATEMENT | JS_SWITCH_STATEMENT
)
}
fn is_loop_node(node: &SyntaxNode<JsLanguage>) -> bool {
use rome_js_syntax::JsSyntaxKind::*;
matches!(
node.kind(),
JS_DO_WHILE_STATEMENT
| JS_FOR_OF_STATEMENT
| JS_FOR_IN_STATEMENT
| JS_FOR_STATEMENT
| JS_WHILE_STATEMENT
)
}
/// Returns whether use of the given node results in a penalty for increasing
/// the complexity of the structure of the function.
///
/// The structure of a function is mostly defined by its control flow, although
/// there are some node types that we consider as increasing its structural
/// complexity even though they do not affect its control flow.
///
/// A prime example of this is the `with` statement, which does not affect
/// control flow, but which is considered to increase structural complexity
/// since developers will need to spend additional effort tracing the scope of
/// variables.
///
/// Do note that the SonarSource paper makes no mention of the `with` statement
/// specifically (probably because it's highly specific to JavaScript), so its
/// inclusion here is a personal judgement call.
fn receives_structural_penalty(node: &SyntaxNode<JsLanguage>) -> bool {
use rome_js_syntax::JsSyntaxKind::*;
receives_nesting_penalty(node)
|| matches!(node.kind(), JS_FINALLY_CLAUSE | JS_WITH_STATEMENT)
|| JsBreakStatement::cast_ref(node)
.and_then(|js_break| js_break.label_token())
.is_some()
|| JsContinueStatement::cast_ref(node)
.and_then(|js_continue| js_continue.label_token())
.is_some()
}
/// Returns whether use of the given node receives an additional penalty based
/// on the level of nesting in which it occurs.
///
/// Note: This is a strict subset of the nodes that receive a structural penalty.
fn receives_nesting_penalty(node: &SyntaxNode<JsLanguage>) -> bool {
use rome_js_syntax::JsSyntaxKind::*;
is_loop_node(node)
|| matches!(
node.kind(),
JS_CATCH_CLAUSE | JS_CONDITIONAL_EXPRESSION | JS_IF_STATEMENT | JS_SWITCH_STATEMENT
)
}
#[derive(Clone, Default)]
pub struct ComplexityScore {
calculated_score: u8,
}
/// Options for the rule `noNestedModuleImports`.
#[derive(Deserialize, Serialize, Debug, Clone, Bpaf)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ComplexityOptions {
/// The maximum complexity score that we allow. Anything higher is considered excessive.
pub max_allowed_complexity: u8,
}
impl Default for ComplexityOptions {
fn default() -> Self {
Self {
max_allowed_complexity: 10,
}
}
}
impl FromStr for ComplexityOptions {
type Err = ();
fn from_str(_s: &str) -> Result<Self, Self::Err> {
Ok(Self::default())
}
}
impl VisitJsonNode for ComplexityOptions {}
impl VisitNode<JsonLanguage> for ComplexityOptions {
fn visit_member_name(
&mut self,
node: &JsonSyntaxNode,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(node, &["maxAllowedComplexity"], 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();
if name_text == "maxAllowedComplexity" {
if let Some(value) = value
.as_json_number_value()
.and_then(|number_value| u8::from_str(&number_value.syntax().to_string()).ok())
// Don't allow 0 or no code would pass.
// And don't allow MAX_SCORE or we can't detect exceeding it.
.filter(|&number| number > 0 && number < MAX_SCORE)
{
self.max_allowed_complexity = value;
} else {
diagnostics.push(
DeserializationDiagnostic::new(markup! {
"The field "<Emphasis>"maxAllowedComplexity"</Emphasis>
" must contain an integer between 1 and "{MAX_SCORE - 1}
})
.with_range(value.range()),
);
}
}
Some(())
}
}
| 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/no_useless_empty_export.rs | crates/rome_js_analyze/src/analyzers/nursery/no_useless_empty_export.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{AnyJsModuleItem, JsExport, JsModuleItemList, JsSyntaxToken};
use rome_rowan::{AstNode, AstSeparatedList, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Disallow empty exports that don't change anything in a module file.
///
/// An empty `export {}` is sometimes useful to turn a file that would otherwise be a script into a module.
/// Per the [TypeScript Handbook Modules page](https://www.typescriptlang.org/docs/handbook/modules.html):
///
/// > In TypeScript, just as in ECMAScript 2015,
/// > any file containing a top-level import or export is considered a module.
/// > Conversely, a file without any top-level import or export declarations is treated as a script
/// > whose contents are available in the global scope.
///
/// However, an `export {}` statement does nothing if there are any other top-level import or export in the file.
///
/// Source: https://typescript-eslint.io/rules/no-useless-empty-export/
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// import { A } from "module";
/// export {};
/// ```
///
/// ```js,expect_diagnostic
/// export const A = 0;
/// export {};
/// ```
///
/// ## Valid
///
/// ```js
/// export {};
/// ```
///
pub(crate) NoUselessEmptyExport {
version: "next",
name: "noUselessEmptyExport",
recommended: true,
}
}
impl Rule for NoUselessEmptyExport {
type Query = Ast<JsExport>;
/// The first import or export that makes useless the empty export.
type State = JsSyntaxToken;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if is_empty_export(node) {
let module_item_list = JsModuleItemList::cast(node.syntax().parent()?)?;
// allow reporting an empty export that precedes another empty export.
let mut ignore_empty_export = true;
for module_item in module_item_list {
match module_item {
AnyJsModuleItem::AnyJsStatement(_) => {}
AnyJsModuleItem::JsImport(import) => return import.import_token().ok(),
AnyJsModuleItem::JsExport(export) => {
if !is_empty_export(&export) {
return export.export_token().ok();
}
if !ignore_empty_export {
return export.export_token().ok();
}
if node == &export {
ignore_empty_export = false
}
}
}
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, token: &Self::State) -> Option<RuleDiagnostic> {
Some(
RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
markup! {
"This empty "<Emphasis>"export"</Emphasis>" is useless because there's another "<Emphasis>"export"</Emphasis>" or "<Emphasis>"import"</Emphasis>"."
},
).detail(token.text_trimmed_range(), markup! {
"This "<Emphasis>{token.text_trimmed()}</Emphasis>" makes useless the empty export."
}),
)
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
mutation.remove_node(ctx.query().clone());
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! { "Remove this useless empty export." }.to_owned(),
mutation,
})
}
}
fn is_empty_export(export: &JsExport) -> bool {
(|| -> Option<bool> {
Some(
export
.export_clause()
.ok()?
.as_js_export_named_clause()?
.specifiers()
.iter()
.count()
== 0,
)
})()
.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/nursery/no_control_characters_in_regex.rs | crates/rome_js_analyze/src/analyzers/nursery/no_control_characters_in_regex.rs | use crate::utils::escape_string;
use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{
AnyJsExpression, JsCallArguments, JsCallExpression, JsNewExpression, JsRegexLiteralExpression,
JsStringLiteralExpression,
};
use rome_rowan::{declare_node_union, AstNode, AstSeparatedList};
use std::{iter::Peekable, str::Chars};
declare_rule! {
/// Prevents from having control characters and some escape sequences that match control characters in regular expressions.
///
/// Control characters are hidden special characters that are numbered from 0 to 31 in the ASCII system.
/// They're not commonly used in JavaScript text. So, if you see them in a pattern (called a regular expression), it's probably a mistake.
///
/// The following elements of regular expression patterns are considered possible errors in typing and are therefore disallowed by this rule:
///
/// - Hexadecimal character escapes from `\x00` to `\x1F`
/// - Unicode character escapes from `\u0000` to `\u001F`
/// - Unicode code point escapes from `\u{0}` to `\u{1F}`
/// - Unescaped raw characters from U+0000 to U+001F
///
/// Control escapes such as `\t` and `\n` are allowed by this rule.
///
/// Source: https://eslint.org/docs/latest/rules/no-control-regex
///
/// ## Examples
///
/// ### Invalid
/// ```js,expect_diagnostic
/// var pattern1 = /\x00/;
/// ```
/// ```js,expect_diagnostic
/// var pattern2 = /\x0C/;
/// ```
/// ```js,expect_diagnostic
/// var pattern3 = /\x1F/;
/// ```
/// ```js,expect_diagnostic
/// var pattern4 = /\u000C/;
/// ```
/// ```js,expect_diagnostic
/// var pattern5 = /\u{C}/u;
/// ```
/// ```js,expect_diagnostic
/// var pattern7 = new RegExp("\x0C");
/// ```
/// ```js,expect_diagnostic
/// var pattern7 = new RegExp("\\x0C");
/// ```
///
/// ### Valid
/// ```js
/// var pattern1 = /\x20/;
/// var pattern2 = /\u0020/;
/// var pattern3 = /\u{20}/u;
/// var pattern4 = /\t/;
/// var pattern5 = /\n/;
/// var pattern6 = new RegExp("\x20");
/// ```
///
pub(crate) NoControlCharactersInRegex {
version: "next",
name: "noControlCharactersInRegex",
recommended: true,
}
}
declare_node_union! {
pub(crate) RegexExpressionLike = JsNewExpression | JsCallExpression | JsRegexLiteralExpression
}
fn decode_hex_character_to_code_point(iter: &mut Peekable<Chars>) -> Option<(String, i64)> {
let first = iter.next()?;
let second = iter.next()?;
let digits = format!("{first}{second}");
let code_point = i64::from_str_radix(&digits, 16).ok()?;
Some((digits, code_point))
}
fn decode_unicode_escape_to_code_point(iter: &mut Peekable<Chars>) -> Option<(String, i64)> {
let mut digits = String::new();
// Loop 4 times as unicode escape sequence has exactly 4 hexadecimal digits
for _ in 0..4 {
if let Some(&c) = iter.peek() {
match c {
'0'..='9' | 'a'..='f' | 'A'..='F' => digits.push(iter.next()?),
_ => continue,
}
}
}
let code_point = i64::from_str_radix(digits.as_str(), 16).ok()?;
Some((digits, code_point))
}
fn decode_escaped_code_point_to_code_point(iter: &mut Peekable<Chars>) -> Option<(String, i64)> {
let mut digits = String::new();
if iter.peek() == Some(&'{') {
iter.next();
while let Some(&c) = iter.peek() {
if c == '}' {
iter.next();
let code_point = i64::from_str_radix(&digits, 16).ok()?;
return Some((format!("{{{}}}", digits), code_point));
} else {
digits.push(iter.next()?);
}
}
}
None
}
fn add_control_character_to_vec(
prefix: &str,
iter: &mut Peekable<Chars>,
control_characters: &mut Vec<String>,
decode: fn(&mut Peekable<Chars>) -> Option<(String, i64)>,
) {
if let Some((s, code_point)) = decode(iter) {
// ASCII control characters are represented by code points from 0 to 31
if (0..=31).contains(&code_point) {
control_characters.push(format!("{prefix}{s}"));
}
}
}
/// Collecting control characters for regex. The following characters in regular expression patterns are considered as control characters:
/// - Hexadecimal character escapes from `\x00` to `\x1F`.
/// - Unicode character escapes from `\u0000` to `\u001F`.
/// - Unicode code point escapes range from `\u{0}` to `\u{1F}`.
/// - The Unicode flag must be set as true in order for these Unicode code point escapes to work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode.
/// - Unescaped raw characters from U+0000 to U+001F.
fn collect_control_characters(pattern: String, flags: Option<String>) -> Option<Vec<String>> {
let mut control_characters: Vec<String> = Vec::new();
let is_unicode_flag_set = flags.unwrap_or_default().contains('u');
let mut iter = pattern.chars().peekable();
while let Some(c) = iter.next() {
match c {
'\\' => match iter.next() {
Some('x') => add_control_character_to_vec(
"\\x",
&mut iter,
&mut control_characters,
decode_hex_character_to_code_point,
),
Some('u') if is_unicode_flag_set => add_control_character_to_vec(
"\\u",
&mut iter,
&mut control_characters,
decode_escaped_code_point_to_code_point,
),
Some('u') => add_control_character_to_vec(
"\\u",
&mut iter,
&mut control_characters,
decode_unicode_escape_to_code_point,
),
Some('\\') => continue,
_ => break,
},
_ => continue,
}
}
if !control_characters.is_empty() {
Some(control_characters)
} else {
None
}
}
fn collect_control_characters_from_expression(
callee: &AnyJsExpression,
js_call_arguments: &JsCallArguments,
) -> Option<Vec<String>> {
if callee.as_js_reference_identifier()?.has_name("RegExp") {
let mut args = js_call_arguments.args().iter();
let raw_pattern = args
.next()
.and_then(|arg| arg.ok())
.and_then(|arg| JsStringLiteralExpression::cast_ref(arg.syntax()))
.and_then(|js_string_literal| js_string_literal.inner_string_text().ok())?
.to_string();
let pattern = escape_string(&raw_pattern).unwrap_or(raw_pattern);
let regexp_flags = args
.next()
.and_then(|arg| arg.ok())
.and_then(|arg| JsStringLiteralExpression::cast_ref(arg.syntax()))
.map(|js_string_literal| js_string_literal.text());
return collect_control_characters(pattern, regexp_flags);
}
None
}
impl Rule for NoControlCharactersInRegex {
type Query = Ast<RegexExpressionLike>;
type State = Vec<String>;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
match node {
RegexExpressionLike::JsNewExpression(js_new_expression) => {
collect_control_characters_from_expression(
&js_new_expression.callee().ok()?,
&js_new_expression.arguments()?,
)
}
RegexExpressionLike::JsCallExpression(js_call_expression) => {
collect_control_characters_from_expression(
&js_call_expression.callee().ok()?,
&js_call_expression.arguments().ok()?,
)
}
RegexExpressionLike::JsRegexLiteralExpression(js_regex_literal_expression) => {
collect_control_characters(
js_regex_literal_expression.pattern().ok()?,
js_regex_literal_expression.flags().ok(),
)
}
}
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
markup! {
"Unexpected control character(s) in regular expression: "<Emphasis>{state.join(", ")}</Emphasis>""
},
).note(
markup! {
"Control characters are unusual and potentially incorrect inputs, so they are disallowed."
}
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_collect_control_characters() {
assert_eq!(
collect_control_characters(String::from("\\x00\\x0F\\u0010\\u001F"), None),
Some(vec![
String::from("\\x00"),
String::from("\\x0F"),
String::from("\\u0010"),
String::from("\\u001F")
])
);
assert_eq!(
collect_control_characters(String::from("\\u{0}\\u{1F}"), Some(String::from("u"))),
Some(vec![String::from("\\u{0}"), String::from("\\u{1F}")])
);
assert_eq!(
collect_control_characters(String::from("\\x20\\u0020\\u{20}\\t\\n"), 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/aria_analyzers/a11y.rs | crates/rome_js_analyze/src/aria_analyzers/a11y.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_analyze::declare_group;
pub(crate) mod no_noninteractive_element_to_interactive_role;
pub(crate) mod use_aria_props_for_role;
pub(crate) mod use_valid_aria_props;
pub(crate) mod use_valid_lang;
declare_group! {
pub (crate) A11y {
name : "a11y" ,
rules : [
self :: no_noninteractive_element_to_interactive_role :: NoNoninteractiveElementToInteractiveRole ,
self :: use_aria_props_for_role :: UseAriaPropsForRole ,
self :: use_valid_aria_props :: UseValidAriaProps ,
self :: use_valid_lang :: UseValidLang ,
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/aria_analyzers/nursery.rs | crates/rome_js_analyze/src/aria_analyzers/nursery.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_analyze::declare_group;
pub(crate) mod no_aria_unsupported_elements;
pub(crate) mod no_noninteractive_tabindex;
pub(crate) mod no_redundant_roles;
pub(crate) mod use_aria_prop_types;
declare_group! {
pub (crate) Nursery {
name : "nursery" ,
rules : [
self :: no_aria_unsupported_elements :: NoAriaUnsupportedElements ,
self :: no_noninteractive_tabindex :: NoNoninteractiveTabindex ,
self :: no_redundant_roles :: NoRedundantRoles ,
self :: use_aria_prop_types :: UseAriaPropTypes ,
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/aria_analyzers/a11y/no_noninteractive_element_to_interactive_role.rs | crates/rome_js_analyze/src/aria_analyzers/a11y/no_noninteractive_element_to_interactive_role.rs | use crate::aria_services::Aria;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_rowan::{AstNode, TextRange};
declare_rule! {
/// Enforce that interactive ARIA roles are not assigned to non-interactive HTML elements.
///
/// Non-interactive HTML elements indicate _content_ and _containers_ in the user interface.
/// Non-interactive elements include `<main>`, `<area>`, `<h1>` (,`<h2>`, etc), `<img>`, `<li>`, `<ul>` and `<ol>`.
///
/// Interactive HTML elements indicate _controls_ in the user interface.
/// Interactive elements include `<a href>`, `<button>`, `<input>`, `<select>`, `<textarea>`.
///
/// [WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) should not be used to convert a non-interactive element to an interactive element.
/// Interactive ARIA roles include `button`, `link`, `checkbox`, `menuitem`, `menuitemcheckbox`, `menuitemradio`, `option`, `radio`, `searchbox`, `switch` and `textbox`.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <h1 role="button">Some text</h1>
/// ```
///
/// ### Valid
///
///
/// ```jsx
/// <span role="button">Some text</span>
/// ```
///
/// ## Accessibility guidelines
///
/// - [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)
///
/// ### Resources
///
/// - [WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro)
/// - [WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets](https://www.w3.org/TR/wai-aria-practices-1.1/#aria_ex)
/// - [Fundamental Keyboard Navigation Conventions](https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_generalnav)
/// - [Mozilla Developer Network - ARIA Techniques](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_button_role#Keyboard_and_focus)
///
pub(crate) NoNoninteractiveElementToInteractiveRole {
version: "12.0.0",
name: "noNoninteractiveElementToInteractiveRole",
recommended: true,
}
}
pub(crate) struct RuleState {
attribute_range: TextRange,
element_name: String,
}
impl Rule for NoNoninteractiveElementToInteractiveRole {
type Query = Aria<AnyJsxElement>;
type State = RuleState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let aria_roles = ctx.aria_roles();
if node.is_element() {
let role_attribute = node.find_attribute_by_name("role")?;
let role_attribute_static_value = role_attribute.as_static_value()?;
let role_attribute_value = role_attribute_static_value.text();
let element_name = node.name().ok()?.as_jsx_name()?.value_token().ok()?;
let attributes = ctx.extract_attributes(&node.attributes());
if aria_roles.is_not_interactive_element(element_name.text_trimmed(), attributes)
&& aria_roles.is_role_interactive(role_attribute_value)
{
// <div> and <span> are considered neither interactive nor non-interactive, depending on the presence or absence of the role attribute.
// We don't report <div> and <span> here, because we cannot determine whether they are interactive or non-interactive.
let role_sensitive_elements = ["div", "span"];
if role_sensitive_elements.contains(&element_name.text_trimmed()) {
return None;
}
return Some(RuleState {
attribute_range: role_attribute.range(),
element_name: element_name.text_trimmed().to_string(),
});
}
}
None
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
state.attribute_range,
markup! {
"The HTML element "<Emphasis>{{&state.element_name}}</Emphasis>" is non-interactive and should not have an interactive role."
},
).note(
markup!{
"Replace "<Emphasis>{{&state.element_name}}</Emphasis>" with a div or a span."
}
))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/aria_analyzers/a11y/use_valid_aria_props.rs | crates/rome_js_analyze/src/aria_analyzers/a11y/use_valid_aria_props.rs | use crate::aria_services::Aria;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_rowan::{AstNode, AstNodeList, TextRange};
declare_rule! {
/// Ensures that ARIA properties `aria-*` are all valid.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx, expect_diagnostic
/// <input className="" aria-labell="" />
/// ```
///
/// ```jsx,expect_diagnostic
/// <div aria-lorem="foobar" aria-ipsum="foobar" />;
/// ```
///
/// ## Accessibility guidelines
/// - [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)
pub(crate) UseValidAriaProps {
version: "12.0.0",
name: "useValidAriaProps",
recommended: true,
}
}
impl Rule for UseValidAriaProps {
type Query = Aria<AnyJsxElement>;
type State = Vec<(TextRange, String)>;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let aria_properties = ctx.aria_properties();
// check attributes that belong only to HTML elements
if node.is_element() {
let attributes: Vec<_> = node
.attributes()
.iter()
.filter_map(|attribute| {
let attribute = attribute.as_jsx_attribute()?;
let attribute_name =
attribute.name().ok()?.as_jsx_name()?.value_token().ok()?;
if attribute_name.text_trimmed().starts_with("aria-")
&& aria_properties
.get_property(attribute_name.text_trimmed())
.is_none()
{
Some((attribute.range(), attribute_name.to_string()))
} else {
None
}
})
.collect();
if attributes.is_empty() {
None
} else {
Some(attributes)
}
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, attributes: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
let mut diagnostic = RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"The element contains invalid ARIA attribute(s)"
},
);
for (range, attribute_name) in attributes {
diagnostic = diagnostic.detail(
range,
markup! {
<Emphasis>{attribute_name}</Emphasis>" is not a valid ARIA attribute."
},
);
}
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/aria_analyzers/a11y/use_valid_lang.rs | crates/rome_js_analyze/src/aria_analyzers/a11y/use_valid_lang.rs | use crate::aria_services::Aria;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_rowan::{AstNode, TextRange};
declare_rule! {
/// Ensure that the attribute passed to the `lang` attribute is a correct ISO language and/or country.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <html lang="lorem" />
/// ```
///
/// ```jsx,expect_diagnostic
/// <html lang="en-babab" />
/// ```
///
/// ```jsx,expect_diagnostic
/// <html lang="en-GB-typo" />
/// ```
///
/// ### Valid
///
/// ```jsx
/// <Html lang="en-babab" />
/// ```
pub(crate) UseValidLang {
version: "12.0.0",
name: "useValidLang",
recommended: true,
}
}
enum InvalidKind {
Language,
Country,
Value,
}
pub(crate) struct UseValidLangState {
invalid_kind: InvalidKind,
attribute_range: TextRange,
}
impl Rule for UseValidLang {
type Query = Aria<AnyJsxElement>;
type State = UseValidLangState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let element_text = node.name().ok()?.as_jsx_name()?.value_token().ok()?;
if element_text.text_trimmed() == "html" {
let attribute = node.find_attribute_by_name("lang")?;
let attribute_value = attribute.initializer()?.value().ok()?;
let attribute_static_value = attribute_value.as_static_value()?;
let attribute_text = attribute_static_value.text();
let mut split_value = attribute_text.split('-');
match (split_value.next(), split_value.next()) {
(Some(language), Some(country)) => {
if !ctx.is_valid_iso_language(language) {
return Some(UseValidLangState {
attribute_range: attribute_value.range(),
invalid_kind: InvalidKind::Language,
});
} else if !ctx.is_valid_iso_country(country) {
return Some(UseValidLangState {
attribute_range: attribute_value.range(),
invalid_kind: InvalidKind::Country,
});
} else if split_value.next().is_some() {
return Some(UseValidLangState {
attribute_range: attribute_value.range(),
invalid_kind: InvalidKind::Value,
});
}
}
(Some(language), None) => {
if !ctx.is_valid_iso_language(language) {
return Some(UseValidLangState {
attribute_range: attribute_value.range(),
invalid_kind: InvalidKind::Language,
});
}
}
_ => {}
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let mut diagnostic = RuleDiagnostic::new(
rule_category!(),
state.attribute_range,
markup! {
"Provide a valid value for the "<Emphasis>"lang"</Emphasis>" attribute."
},
);
diagnostic = match state.invalid_kind {
InvalidKind::Language => {
let languages = ctx.iso_language_list();
let languages = if languages.len() > 15 {
&languages[..15]
} else {
languages
};
diagnostic.footer_list("Some of valid languages:", languages)
}
InvalidKind::Country => {
let countries = ctx.iso_country_list();
let countries = if countries.len() > 15 {
&countries[..15]
} else {
countries
};
diagnostic.footer_list("Some of valid countries:", countries)
}
InvalidKind::Value => diagnostic,
};
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/aria_analyzers/a11y/use_aria_props_for_role.rs | crates/rome_js_analyze/src/aria_analyzers/a11y/use_aria_props_for_role.rs | use crate::aria_services::Aria;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_js_syntax::JsxAttribute;
use rome_rowan::AstNode;
declare_rule! {
/// Enforce that elements with ARIA roles must have all required ARIA attributes for that role.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <span role="checkbox"></span>
/// ```
///
/// ```jsx,expect_diagnostic
/// <span role="heading"></span>
/// ```
///
/// ### Valid
///
/// ```jsx
/// <span role="checkbox" aria-checked="true"></span>
/// ```
///
/// ```jsx
/// <span role="heading" aria-level="1"></span>
/// ```
///
///
/// ## Accessibility guidelines
/// - [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)
///
/// ### Resources
/// - [ARIA Spec, Roles](https://www.w3.org/TR/wai-aria/#roles)
/// - [Chrome Audit Rules, AX_ARIA_03](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules#ax_aria_03)
pub(crate) UseAriaPropsForRole {
version: "11.0.0",
name: "useAriaPropsForRole",
recommended: true,
}
}
#[derive(Default, Debug)]
pub(crate) struct UseAriaPropsForRoleState {
missing_aria_props: Vec<String>,
attribute: Option<(JsxAttribute, String)>,
}
impl UseAriaPropsForRoleState {
pub(crate) fn as_diagnostic(&self) -> Option<RuleDiagnostic> {
if self.missing_aria_props.is_empty() {
return None;
}
self.attribute.as_ref().map(|(attribute, role_name)| {
let joined_attributes = &self.missing_aria_props.join(", ");
let description = format!("The element with the {role_name} ARIA role does not have the required ARIA attributes: {}.", joined_attributes);
RuleDiagnostic::new(
rule_category!(),
attribute.range(),
markup! {
"The element with the "<Emphasis>{role_name}</Emphasis>" ARIA role does not have the required ARIA attributes."
},
)
.description(description)
.footer_list(markup! { "Missing ARIA prop(s):" }, &self.missing_aria_props)
})
}
}
impl Rule for UseAriaPropsForRole {
type Query = Aria<AnyJsxElement>;
type State = UseAriaPropsForRoleState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let roles = ctx.aria_roles();
let is_inside_element = node
.syntax()
.ancestors()
.find_map(|ancestor| {
AnyJsxElement::cast(ancestor)
.map(|element| Some(element.is_element()))
.unwrap_or(None)
})
.unwrap_or(false);
if is_inside_element {
let role_attribute = node.find_attribute_by_name("role")?;
let name = role_attribute
.initializer()?
.value()
.ok()?
.as_jsx_string()?
.inner_string_text()
.ok()?;
let role = roles.get_role(name.text());
let missing_aria_props: Vec<_> = role
.into_iter()
.flat_map(|role| role.properties())
.filter_map(|(property_name, required)| {
if *required {
let attribute = node.find_attribute_by_name(property_name);
if attribute.is_none() {
Some(property_name.to_string())
} else {
None
}
} else {
None
}
})
.collect();
if !missing_aria_props.is_empty() {
return Some(UseAriaPropsForRoleState {
attribute: Some((role_attribute, name.text().to_string())),
missing_aria_props,
});
}
}
None
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
state.as_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/aria_analyzers/nursery/no_noninteractive_tabindex.rs | crates/rome_js_analyze/src/aria_analyzers/nursery/no_noninteractive_tabindex.rs | use crate::aria_services::Aria;
use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic};
use rome_aria::AriaRoles;
use rome_console::markup;
use rome_js_syntax::{
jsx_ext::AnyJsxElement, AnyJsxAttributeValue, JsNumberLiteralExpression,
JsStringLiteralExpression, JsUnaryExpression, TextRange,
};
use rome_rowan::{declare_node_union, AstNode};
declare_rule! {
/// Enforce that `tabIndex` is not assigned to non-interactive HTML elements.
///
/// When using the tab key to navigate a webpage, limit it to interactive elements.
/// You don't need to add tabindex to items in an unordered list as assistive technology can navigate through the HTML.
/// Keep the tab ring small, which is the order of elements when tabbing, for a more efficient and accessible browsing experience.
///
/// ESLint (eslint-plugin-jsx-a11y) Equivalent: [no-noninteractive-tabindex](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/main/docs/rules/no-noninteractive-tabindex.md)
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <div tabIndex="0" />
/// ```
///
/// ```jsx,expect_diagnostic
/// <div role="article" tabIndex="0" />
/// ```
///
/// ```jsx,expect_diagnostic
/// <article tabIndex="0" />
/// ```
///
/// ## Valid
///
/// ```jsx
/// <div />
/// ```
///
/// ```jsx
/// <MyButton tabIndex={0} />
/// ```
///
/// ```jsx
/// <article tabIndex="-1" />
/// ```
///
pub(crate) NoNoninteractiveTabindex {
version: "12.1.0",
name: "noNoninteractiveTabindex",
recommended: false,
}
}
declare_node_union! {
/// Subset of expressions supported by this rule.
///
/// ## Examples
///
/// - `JsStringLiteralExpression` — `"5"`
/// - `JsNumberLiteralExpression` — `5`
/// - `JsUnaryExpression` — `+5` | `-5`
///
pub(crate) AnyNumberLikeExpression = JsStringLiteralExpression | JsNumberLiteralExpression | JsUnaryExpression
}
impl AnyNumberLikeExpression {
/// Returns the value of a number-like expression; it returns the expression
/// text for literal expressions. However, for unary expressions, it only
/// returns the value for signed numeric expressions.
pub(crate) fn value(&self) -> Option<String> {
match self {
AnyNumberLikeExpression::JsStringLiteralExpression(string_literal) => {
return Some(string_literal.inner_string_text().ok()?.to_string());
}
AnyNumberLikeExpression::JsNumberLiteralExpression(number_literal) => {
return Some(number_literal.value_token().ok()?.to_string());
}
AnyNumberLikeExpression::JsUnaryExpression(unary_expression) => {
if unary_expression.is_signed_numeric_literal().ok()? {
return Some(unary_expression.text());
}
}
}
None
}
}
pub(crate) struct RuleState {
attribute_range: TextRange,
element_name: String,
}
impl Rule for NoNoninteractiveTabindex {
type Query = Aria<AnyJsxElement>;
type State = RuleState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if !node.is_element() {
return None;
}
let element_name = node.name().ok()?.as_jsx_name()?.value_token().ok()?;
let aria_roles = ctx.aria_roles();
let attributes = ctx.extract_attributes(&node.attributes());
if aria_roles.is_not_interactive_element(element_name.text_trimmed(), attributes) {
let tabindex_attribute = node.find_attribute_by_name("tabIndex")?;
let tabindex_attribute_value = tabindex_attribute.initializer()?.value().ok()?;
if attribute_has_negative_tabindex(&tabindex_attribute_value)? {
return None;
}
let role_attribute = node.find_attribute_by_name("role");
let Some(role_attribute) = role_attribute else {
return Some(RuleState {
attribute_range: tabindex_attribute.range(),
element_name: element_name.text_trimmed().to_string(),
})
};
let role_attribute_value = role_attribute.initializer()?.value().ok()?;
if attribute_has_interactive_role(&role_attribute_value, aria_roles)? {
return None;
}
return Some(RuleState {
attribute_range: tabindex_attribute.range(),
element_name: element_name.text_trimmed().to_string(),
});
}
None
}
fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
Some(
RuleDiagnostic::new(
rule_category!(),
state.attribute_range,
markup! {
"The HTML element "<Emphasis>{{&state.element_name}}</Emphasis>" is non-interactive. Do not use "<Emphasis>"tabIndex"</Emphasis>"."
},
)
.note(markup! {
"Adding non-interactive elements to the keyboard navigation flow can confuse users."
}),
)
}
}
/// Verifies if number string is an integer less than 0.
/// Non-integer numbers are considered valid.
fn is_negative_tabindex(number_like_string: &str) -> bool {
let number_string_result = number_like_string.trim().parse::<i32>();
match number_string_result {
Ok(number) => number < 0,
Err(_) => true,
}
}
/// Checks if the given tabindex attribute value has negative integer or not.
fn attribute_has_negative_tabindex(
tabindex_attribute_value: &AnyJsxAttributeValue,
) -> Option<bool> {
match tabindex_attribute_value {
AnyJsxAttributeValue::JsxString(jsx_string) => {
let value = jsx_string.inner_string_text().ok()?.to_string();
Some(is_negative_tabindex(&value))
}
AnyJsxAttributeValue::JsxExpressionAttributeValue(value) => {
let expression = value.expression().ok()?;
let expression_value =
AnyNumberLikeExpression::cast_ref(expression.syntax())?.value()?;
Some(is_negative_tabindex(&expression_value))
}
_ => None,
}
}
/// Checks if the given role attribute value is interactive or not based on ARIA roles.
fn attribute_has_interactive_role(
role_attribute_value: &AnyJsxAttributeValue,
aria_roles: &AriaRoles,
) -> Option<bool> {
Some(aria_roles.is_role_interactive(role_attribute_value.as_static_value()?.text()))
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/aria_analyzers/nursery/use_aria_prop_types.rs | crates/rome_js_analyze/src/aria_analyzers/nursery/use_aria_prop_types.rs | use crate::aria_services::Aria;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Rule, RuleDiagnostic};
use rome_aria::AriaPropertyTypeEnum;
use rome_console::markup;
use rome_js_syntax::{JsSyntaxToken, JsxAttribute, TextRange};
use rome_rowan::AstNode;
use std::slice::Iter;
declare_rule! {
/// Enforce that ARIA state and property values are valid.
///
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx, expect_diagnostic
/// <span role="checkbox" aria-checked="test">some text</span>
/// ```
///
/// ```jsx, expect_diagnostic
/// <span aria-labelledby="">some text</span>
/// ```
///
/// ```jsx, expect_diagnostic
/// <span aria-valuemax="hey">some text</span>
/// ```
///
/// ```jsx, expect_diagnostic
/// <span aria-orientation="hey">some text</span>
/// ```
///
/// ### Valid
///
/// ```jsx
/// <>
/// <span role="checkbox" aria-checked={checked} >some text</span>
/// <span aria-labelledby="fooId barId" >some text</span>
/// </>
/// ```
///
/// ## Accessibility guidelines
/// - [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)
///
/// ### Resources
/// - [ARIA Spec, States and Properties](https://www.w3.org/TR/wai-aria/#states_and_properties)
/// - [Chrome Audit Rules, AX_ARIA_04](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules#ax_aria_04)
pub(crate) UseAriaPropTypes {
version: "12.0.0",
name: "useAriaPropTypes",
recommended: false,
}
}
pub(crate) struct UseAriaProptypesState {
attribute_value_range: TextRange,
allowed_values: Iter<'static, &'static str>,
attribute_name: JsSyntaxToken,
property_type: AriaPropertyTypeEnum,
}
impl Rule for UseAriaPropTypes {
type Query = Aria<JsxAttribute>;
type State = UseAriaProptypesState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let aria_properties = ctx.aria_properties();
let attribute_name = node.name().ok()?.as_jsx_name()?.value_token().ok()?;
if let Some(aria_property) = aria_properties.get_property(attribute_name.text_trimmed()) {
let attribute_value_range = node.range();
let attribute_static_value = node.as_static_value()?;
let attribute_text = attribute_static_value.text();
if !aria_property.contains_correct_value(attribute_text) {
return Some(UseAriaProptypesState {
attribute_value_range,
allowed_values: aria_property.values(),
attribute_name,
property_type: aria_property.property_type(),
});
}
}
None
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let attribute_name = state.attribute_name.text_trimmed();
let diagnostic = RuleDiagnostic::new(
rule_category!(),
state.attribute_value_range,
markup! {
"The value of the ARIA attribute "<Emphasis>{attribute_name}</Emphasis>" is not correct."
},
);
let diagnostic = match state.property_type {
AriaPropertyTypeEnum::Boolean => {
diagnostic.footer_list(
markup!{
"The only supported values for the "<Emphasis>{attribute_name}</Emphasis>" property is one of the following:"
},
&["true", "false"]
)
}
AriaPropertyTypeEnum::Integer => {
diagnostic.note(
markup!{
"The only value supported is a number without fractional components."
}
)
}
AriaPropertyTypeEnum::Id |
AriaPropertyTypeEnum::Idlist |
AriaPropertyTypeEnum::String => {
diagnostic.note(
markup!{
"The only supported value is text."
}
)
}
AriaPropertyTypeEnum::Number => {
diagnostic.note(
markup!{
"The only supported value is number."
}
)
}
AriaPropertyTypeEnum::Token => {
diagnostic.footer_list(
markup!{
"The only supported value for the "<Emphasis>{attribute_name}</Emphasis>" property is one of the following:"
},
state.allowed_values.as_slice()
)
}
AriaPropertyTypeEnum::Tokenlist => {
diagnostic.footer_list(
markup!{
"The values supported for "<Emphasis>{attribute_name}</Emphasis>" property are one or more of the following:"
},
state.allowed_values.as_slice()
)
}
AriaPropertyTypeEnum::Tristate => {
diagnostic.footer_list(
markup!{
"The only supported value for the "<Emphasis>{attribute_name}</Emphasis>" property one of the following:"
},
&["true", "false", "mixed"]
)
}
};
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/aria_analyzers/nursery/no_redundant_roles.rs | crates/rome_js_analyze/src/aria_analyzers/nursery/no_redundant_roles.rs | use crate::{aria_services::Aria, JsRuleAction};
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Rule, RuleDiagnostic};
use rome_aria::{roles::AriaRoleDefinition, AriaRoles};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{
jsx_ext::AnyJsxElement, AnyJsxAttributeValue, JsxAttribute, JsxAttributeList,
};
use rome_rowan::{AstNode, BatchMutationExt};
declare_rule! {
/// Enforce explicit `role` property is not the same as implicit/default role property on an element.
///
/// ESLint (eslint-plugin-jsx-a11y) Equivalent: [no-redundant-roles](https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/main/docs/rules/no-redundant-roles.md)
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <article role='article'></article>
/// ```
///
/// ```jsx,expect_diagnostic
/// <button role='button'></button>
/// ```
///
/// ```jsx,expect_diagnostic
/// <h1 role='heading' aria-level='1'>title</h1>
/// ```
///
/// ## Valid
///
/// ```jsx
/// <article role='presentation'></article>
/// ```
///
/// ```jsx
/// <Button role='button'></Button>
/// ```
///
/// ```jsx
/// <span></span>
/// ```
///
pub(crate) NoRedundantRoles {
version: "12.1.0",
name: "noRedundantRoles",
recommended: true,
}
}
pub(crate) struct RuleState {
redundant_attribute: JsxAttribute,
redundant_attribute_value: AnyJsxAttributeValue,
element_name: String,
}
impl Rule for NoRedundantRoles {
type Query = Aria<AnyJsxElement>;
type State = RuleState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let aria_roles = ctx.aria_roles();
let (element_name, attributes) = get_element_name_and_attributes(node)?;
let attribute_name_to_values = ctx.extract_attributes(&attributes)?;
let implicit_role =
aria_roles.get_implicit_role(&element_name, &attribute_name_to_values)?;
let role_attribute = node.find_attribute_by_name("role")?;
let role_attribute_value = role_attribute.initializer()?.value().ok()?;
let explicit_role = get_explicit_role(aria_roles, &role_attribute_value)?;
let is_redundant = implicit_role.type_name() == explicit_role.type_name();
if is_redundant {
return Some(RuleState {
redundant_attribute: role_attribute,
redundant_attribute_value: role_attribute_value,
element_name: element_name.to_string(),
});
}
None
}
fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let binding = state.redundant_attribute_value.as_static_value()?;
let role_attribute = binding.text();
let element = state.element_name.to_string();
Some(RuleDiagnostic::new(
rule_category!(),
state.redundant_attribute_value.range(),
markup! {
"Using the role attribute '"{role_attribute}"' on the '"{element}"' element is redundant."
},
))
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
mutation.remove_node(state.redundant_attribute.clone());
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Remove the "<Emphasis>"role"</Emphasis>" attribute." }.to_owned(),
mutation,
})
}
}
fn get_element_name_and_attributes(node: &AnyJsxElement) -> Option<(String, JsxAttributeList)> {
match node {
AnyJsxElement::JsxOpeningElement(elem) => {
let token = elem.name().ok()?;
let element_name = token.as_jsx_name()?.value_token().ok()?;
let trimmed_element_name = element_name.text_trimmed().to_string();
Some((trimmed_element_name, elem.attributes()))
}
AnyJsxElement::JsxSelfClosingElement(elem) => {
let token = &elem.name().ok()?;
let element_name = token.as_jsx_name()?.value_token().ok()?;
let trimmed_element_name = element_name.text_trimmed().to_string();
Some((trimmed_element_name, elem.attributes()))
}
}
}
fn get_explicit_role(
aria_roles: &AriaRoles,
role_attribute_value: &AnyJsxAttributeValue,
) -> Option<&'static dyn AriaRoleDefinition> {
let static_value = role_attribute_value.as_static_value()?;
// If a role attribute has multiple values, the first valid value (specified role) will be used.
// Check: https://www.w3.org/TR/2014/REC-wai-aria-implementation-20140320/#mapping_role
let explicit_role = static_value
.text()
.split(' ')
.find_map(|role| aria_roles.get_role(role))?;
Some(explicit_role)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/aria_analyzers/nursery/no_aria_unsupported_elements.rs | crates/rome_js_analyze/src/aria_analyzers/nursery/no_aria_unsupported_elements.rs | use crate::aria_services::Aria;
use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_rowan::{AstNode, AstNodeList};
declare_rule! {
/// Enforce that elements that do not support ARIA roles, states, and properties do not have those attributes.
///
/// Source: https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/main/docs/rules/aria-unsupported-elements.md
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <meta charset="UTF-8" role="meta" />
/// ```
///
/// ```jsx,expect_diagnostic
/// <html aria-required="true" />
/// ```
///
/// ## Valid
///
/// ```jsx
/// <meta charset="UTF-8" />
/// ```
///
/// ```jsx
/// <html></html>
/// ```
///
///
pub(crate) NoAriaUnsupportedElements {
version: "12.1.0",
name: "noAriaUnsupportedElements",
recommended: true,
}
}
const ARIA_UNSUPPORTED_ELEMENTS: [&str; 4] = ["meta", "html", "script", "style"];
#[derive(Debug)]
enum AttributeKind {
Role,
Aria,
}
impl AttributeKind {
/// Converts an [AttributeKind] to a string.
fn as_str(&self) -> &'static str {
match self {
AttributeKind::Role => "role",
AttributeKind::Aria => "aria-*",
}
}
}
#[derive(Debug)]
pub struct RuleState {
attribute_kind: AttributeKind,
}
impl Rule for NoAriaUnsupportedElements {
type Query = Aria<AnyJsxElement>;
type State = RuleState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let aria_properties = ctx.aria_properties();
let element_name = node.name().ok()?.as_jsx_name()?.value_token().ok()?;
let element_name = element_name.text_trimmed();
if ARIA_UNSUPPORTED_ELEMENTS.contains(&element_name) {
// Check if the unsupported element has `role` or `aria-*` attribute
let report = node.attributes().iter().find_map(|attribute| {
let attribute = attribute.as_jsx_attribute()?;
let attribute_name = attribute.name().ok()?.as_jsx_name()?.value_token().ok()?;
if attribute_name.text_trimmed().starts_with("aria-")
&& aria_properties
.get_property(attribute_name.text_trimmed())
.is_some()
{
return Some(RuleState {
attribute_kind: AttributeKind::Aria,
});
}
if attribute_name.text_trimmed() == "role" {
return Some(RuleState {
attribute_kind: AttributeKind::Role,
});
}
None
});
return report;
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
let attribute_kind = state.attribute_kind.as_str();
Some(
RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Avoid the "<Emphasis>"role"</Emphasis>" attribute and "<Emphasis>"aria-*"</Emphasis>" attributes when using "<Emphasis>"meta"</Emphasis>", "<Emphasis>"html"</Emphasis>", "<Emphasis>"script"</Emphasis>", and "<Emphasis>"style"</Emphasis>" elements."
},
)
.note(markup! {
"Using "{attribute_kind}" on elements that do not support them can cause issues with screen readers."
}),
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/assists/correctness.rs | crates/rome_js_analyze/src/assists/correctness.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_analyze::declare_group;
pub(crate) mod flip_bin_exp;
pub(crate) mod inline_variable;
pub(crate) mod organize_imports;
declare_group! {
pub (crate) Correctness {
name : "correctness" ,
rules : [
self :: flip_bin_exp :: FlipBinExp ,
self :: inline_variable :: InlineVariable ,
self :: organize_imports :: OrganizeImports ,
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/assists/correctness/flip_bin_exp.rs | crates/rome_js_analyze/src/assists/correctness/flip_bin_exp.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, RefactorKind, Rule};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
JsBinaryExpression, JsBinaryExpressionFields, JsBinaryOperator, JsSyntaxKind, T,
};
use rome_rowan::BatchMutationExt;
use crate::JsRuleAction;
declare_rule! {
/// Provides a refactor to invert the left and right hand side of a binary expression
///
/// ## Examples
///
/// ```js
/// (a < b)
/// ```
pub(crate) FlipBinExp {
version: "0.7.0",
name: "flipBinExp",
recommended: false,
}
}
impl Rule for FlipBinExp {
type Query = Ast<JsBinaryExpression>;
type State = JsSyntaxKind;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
let JsBinaryExpressionFields {
left,
operator_token: _,
right,
} = node.as_fields();
// Ensure the node doesn't have any syntax error
left.ok()?;
right.ok()?;
invert_op(node.operator().ok()?)
}
fn action(ctx: &RuleContext<Self>, op: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let prev_left = node.left().ok()?;
let new_left = node.right().ok()?;
mutation.replace_node(prev_left, new_left);
let prev_op = node.operator_token().ok()?;
let new_op = make::token(*op);
mutation.replace_token(prev_op, new_op);
let prev_right = node.right().ok()?;
let new_right = node.left().ok()?;
mutation.replace_node(prev_right, new_right);
Some(JsRuleAction {
category: ActionCategory::Refactor(RefactorKind::None),
applicability: Applicability::Always,
message: markup! { "Flip Binary Expression" }.to_owned(),
mutation,
})
}
}
fn invert_op(op: JsBinaryOperator) -> Option<JsSyntaxKind> {
match op {
JsBinaryOperator::LessThan => Some(T![>]),
JsBinaryOperator::GreaterThan => Some(T![<]),
JsBinaryOperator::LessThanOrEqual => Some(T![>=]),
JsBinaryOperator::GreaterThanOrEqual => Some(T![<=]),
JsBinaryOperator::Equality => Some(T![==]),
JsBinaryOperator::StrictEquality => Some(T![===]),
JsBinaryOperator::Inequality => Some(T![!=]),
JsBinaryOperator::StrictInequality => Some(T![!==]),
JsBinaryOperator::Plus => Some(T![+]),
JsBinaryOperator::Minus => None,
JsBinaryOperator::Times => Some(T![*]),
JsBinaryOperator::Divide => None,
JsBinaryOperator::Remainder => None,
JsBinaryOperator::Exponent => None,
JsBinaryOperator::LeftShift => None,
JsBinaryOperator::RightShift => None,
JsBinaryOperator::UnsignedRightShift => None,
JsBinaryOperator::BitwiseAnd => Some(T![&]),
JsBinaryOperator::BitwiseOr => Some(T![|]),
JsBinaryOperator::BitwiseXor => Some(T![^]),
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/assists/correctness/organize_imports.rs | crates/rome_js_analyze/src/assists/correctness/organize_imports.rs | use std::{
cell::Cell,
cmp::Ordering,
collections::{btree_map::Entry, BTreeMap},
iter,
mem::take,
};
use rome_analyze::{
context::RuleContext, declare_rule, ActionCategory, Ast, Rule, SourceActionKind,
};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsImportClause, AnyJsModuleItem, AnyJsNamedImport, AnyJsNamedImportSpecifier, JsImport,
JsLanguage, JsModule, JsSyntaxToken, TextRange, TriviaPieceKind, T,
};
use rome_rowan::{
chain_trivia_pieces, syntax::SyntaxTrivia, AstNode, AstNodeExt, AstNodeList, AstSeparatedList,
BatchMutationExt, SyntaxTriviaPiece, TokenText, TriviaPiece,
};
use crate::JsRuleAction;
declare_rule! {
/// Provides a whole-source code action to sort the imports in the file
/// using import groups and natural ordering.
///
/// ## Examples
///
/// ```js
/// import React, {
/// FC,
/// useEffect,
/// useRef,
/// ChangeEvent,
/// KeyboardEvent,
/// } from 'react';
/// import { logger } from '@core/logger';
/// import { reduce, debounce } from 'lodash';
/// import { Message } from '../Message';
/// import { createServer } from '@server/node';
/// import { Alert } from '@ui/Alert';
/// import { repeat, filter, add } from '../utils';
/// import { initializeApp } from '@core/app';
/// import { Popup } from '@ui/Popup';
/// import { createConnection } from '@server/database';
/// ```
pub(crate) OrganizeImports {
version: "11.0.0",
name: "organizeImports",
recommended: false,
}
}
impl Rule for OrganizeImports {
type Query = Ast<JsModule>;
type State = ImportGroups;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let root = ctx.query();
let mut groups = Vec::new();
let mut first_node = None;
let mut nodes = BTreeMap::new();
for item in root.items() {
let import = match item {
AnyJsModuleItem::JsImport(import) => import,
AnyJsModuleItem::AnyJsStatement(_) | AnyJsModuleItem::JsExport(_) => {
// If we have pending nodes and encounter a non-import node, append the nodes to a new group
if let Some(first_node) = first_node.take() {
groups.push(ImportGroup {
first_node,
nodes: take(&mut nodes),
});
}
continue;
}
};
let first_token = import.import_token().ok()?;
// If this is not the first import in the group, check for a group break
if has_empty_line(first_token.leading_trivia()) {
if let Some(first_node) = first_node.take() {
groups.push(ImportGroup {
first_node,
nodes: take(&mut nodes),
});
}
}
// If this is the first import in the group save the leading trivia
// and slot index
if first_node.is_none() {
first_node = Some(import.clone());
}
let source = match import.import_clause().ok()? {
AnyJsImportClause::JsImportBareClause(clause) => clause.source().ok()?,
AnyJsImportClause::JsImportDefaultClause(clause) => clause.source().ok()?,
AnyJsImportClause::JsImportNamedClause(clause) => clause.source().ok()?,
AnyJsImportClause::JsImportNamespaceClause(clause) => clause.source().ok()?,
};
let key = source.inner_string_text().ok()?;
match nodes.entry(ImportKey(key)) {
Entry::Vacant(entry) => {
entry.insert(vec![ImportNode::from(import)]);
}
Entry::Occupied(mut entry) => {
entry.get_mut().push(ImportNode::from(import));
}
}
}
// Flush the remaining nodes
if let Some(first_node) = first_node.take() {
groups.push(ImportGroup { first_node, nodes });
}
groups
.iter()
.any(|group| !group.is_sorted())
.then_some(ImportGroups { groups })
}
fn action(ctx: &RuleContext<Self>, groups: &Self::State) -> Option<JsRuleAction> {
let mut groups_iter = groups.groups.iter();
let mut next_group = groups_iter.next().expect("state is empty");
let old_list = ctx.query().items();
let mut new_list = Vec::new();
let mut items_iter = old_list.iter();
let mut iter = (&mut items_iter).enumerate();
// Iterate other the nodes of the old list
while let Some((item_slot, item)) = iter.next() {
// If the current position in the old list is lower than the start
// of the new group, append the old node to the new list
if item_slot < next_group.first_node.syntax().index() {
new_list.push(item);
continue;
}
// Extract the leading trivia for the whole group from the leading
// trivia for the import token of the first node in the group. If
// the trivia contains empty lines the leading trivia for the group
// comprise all trivia pieces coming before the empty line that's
// closest to the token. Otherwise the group leading trivia is
// created from all the newline and whitespace pieces on the first
// token before the first comment or skipped piece.
let group_first_token = next_group.first_node.import_token().ok()?;
let group_leading_trivia = group_first_token.leading_trivia();
let mut prev_newline = None;
let mut group_leading_trivia: Vec<_> = group_leading_trivia
.pieces()
.enumerate()
.rev()
.find_map(|(index, piece)| {
if piece.is_whitespace() {
return None;
}
let is_newline = piece.is_newline();
if let Some(first_newline) = prev_newline.filter(|_| is_newline) {
return Some(first_newline + 1);
}
prev_newline = is_newline.then_some(index);
None
})
.map_or_else(
|| {
group_leading_trivia
.pieces()
.take_while(is_ascii_whitespace)
.collect()
},
|length| group_leading_trivia.pieces().take(length).collect(),
);
let mut saved_leading_trivia = Vec::new();
let group_leading_pieces = group_leading_trivia.len();
let nodes_iter = next_group
.nodes
.values()
// TODO: Try to merge nodes from the same source
.flat_map(|nodes| nodes.iter())
.enumerate();
for (node_index, import_node) in nodes_iter {
// For each node in the group, pop an item from the old list
// iterator (ignoring `item` itself) and discard it
if node_index > 0 {
iter.next()
.unwrap_or_else(|| panic!("mising node {item_slot} {node_index}"));
}
let first_token = import_node.node.import_token().ok()?;
let mut node = import_node.build_sorted_node();
if node_index == 0 && group_first_token != first_token {
// If this node was not previously in the leading position
// but is being moved there, replace its leading whitespace
// with the group's leading trivia
let group_leading_trivia = group_leading_trivia.drain(..);
let mut token_leading_trivia = first_token.leading_trivia().pieces().peekable();
// Save off the leading whitespace of the token to be
// reused by the import take the place of this node in the list
while let Some(piece) = token_leading_trivia.next_if(is_ascii_whitespace) {
saved_leading_trivia.push(piece);
}
node = node.with_import_token(first_token.with_leading_trivia_pieces(
chain_trivia_pieces(group_leading_trivia, token_leading_trivia),
));
} else if node_index > 0 && group_first_token == first_token {
// If this node used to be in the leading position but
// got moved, remove the group leading trivia from its
// first token
let saved_leading_trivia = saved_leading_trivia.drain(..);
let token_leading_trivia = first_token
.leading_trivia()
.pieces()
.skip(group_leading_pieces);
node = node.with_import_token(first_token.with_leading_trivia_pieces(
chain_trivia_pieces(saved_leading_trivia, token_leading_trivia),
));
}
new_list.push(AnyJsModuleItem::JsImport(node));
}
// Load the next group before moving on to the next item in the old
// list, breaking the loop if there a no remaining groups to insert
next_group = match groups_iter.next() {
Some(entry) => entry,
None => break,
};
}
// Append all remaining nodes to the new list if the loop performed an
// early exit after reaching the last group
new_list.extend(items_iter);
let new_list = make::js_module_item_list(new_list);
let mut mutation = ctx.root().begin();
mutation.replace_node_discard_trivia(old_list, new_list);
Some(JsRuleAction {
category: ActionCategory::Source(SourceActionKind::OrganizeImports),
applicability: Applicability::MaybeIncorrect,
message: markup! { "Organize Imports (Rome)" }.to_owned(),
mutation,
})
}
}
#[derive(Debug)]
pub(crate) struct ImportGroups {
/// The list of all the import groups in the file
groups: Vec<ImportGroup>,
}
#[derive(Debug)]
struct ImportGroup {
/// The import that was at the start of the group before sorting
first_node: JsImport,
/// Multimap storing all the imports for each import source in the group,
/// sorted in natural order
nodes: BTreeMap<ImportKey, Vec<ImportNode>>,
}
impl ImportGroup {
/// Returns true if the nodes in the group are already sorted in the file
fn is_sorted(&self) -> bool {
// The imports are sorted if the start of each node in the `BTreeMap`
// (sorted in natural order) is higher or equal to the previous item in
// the sequence
let mut iter = self.nodes.values().flat_map(|nodes| nodes.iter());
let Some(import_node) = iter.next() else {
return true;
};
if !import_node.is_sorted() {
return false;
}
let mut last = import_node.node.syntax().text_range().start();
iter.all(|import_node| {
let start = import_node.node.syntax().text_range().start();
if start < last {
return false;
}
// Only return false if the node has been fully inspected and was
// found to be unsorted, but continue visiting the remaining
// imports if the node was sorted or contained syntax errors
if !import_node.is_sorted() {
return false;
}
last = start;
true
})
}
}
#[derive(Debug)]
struct ImportNode {
/// The original `JsImport` node this import node was created from
node: JsImport,
/// The number of separators present in the named specifiers list of this node if it has one
separator_count: usize,
/// Map storing all the named import specifiers and their associated trailing separator,
/// sorted in natural order
specifiers: BTreeMap<ImportKey, (AnyJsNamedImportSpecifier, Option<JsSyntaxToken>)>,
}
impl From<JsImport> for ImportNode {
fn from(node: JsImport) -> Self {
let import_clause = node.import_clause().ok();
let mut separator_count = 0;
let specifiers = import_clause.and_then(|import_clause| {
let import_named_clause = match import_clause {
AnyJsImportClause::JsImportBareClause(_)
| AnyJsImportClause::JsImportDefaultClause(_)
| AnyJsImportClause::JsImportNamespaceClause(_) => return None,
AnyJsImportClause::JsImportNamedClause(import_clause) => import_clause,
};
let named_import = import_named_clause.named_import().ok()?;
let AnyJsNamedImport::JsNamedImportSpecifiers(named_import_specifiers) = named_import else {
return None;
};
let mut result = BTreeMap::new();
for element in named_import_specifiers.specifiers().elements() {
let node = element.node.ok()?;
let key = import_specifier_name(&node)?;
let trailing_separator = element.trailing_separator.ok()?;
separator_count += usize::from(trailing_separator.is_some());
result.insert(ImportKey(key), (node, trailing_separator));
}
Some(result)
});
Self {
node,
separator_count,
specifiers: specifiers.unwrap_or_default(),
}
}
}
impl ImportNode {
/// Returns `true` if the named import specifiers of this import node are sorted
fn is_sorted(&self) -> bool {
let mut iter = self
.specifiers
.values()
.map(|(node, _)| node.syntax().text_range().start());
let Some(mut last) = iter.next() else {
return true;
};
iter.all(|value| {
if value < last {
return false;
}
last = value;
true
})
}
/// Build a clone of the original node this import node was created from with its import specifiers sorted
fn build_sorted_node(&self) -> JsImport {
let import = self.node.clone().detach();
let import_clause = import.import_clause();
let import_named_clause =
if let Ok(AnyJsImportClause::JsImportNamedClause(node)) = import_clause {
node
} else {
return import;
};
let named_import = import_named_clause.named_import();
let old_specifiers =
if let Ok(AnyJsNamedImport::JsNamedImportSpecifiers(node)) = named_import {
node
} else {
return import;
};
let element_count = self.specifiers.len();
let last_element = element_count.saturating_sub(1);
let separator_count = self.separator_count.max(last_element);
let needs_newline: Cell<Option<Option<JsSyntaxToken>>> = Cell::new(None);
let items = self
.specifiers
.values()
.enumerate()
.map(|(index, (node, sep))| {
let is_last = index == last_element;
let mut node = node.clone().detach();
let prev_token = match node.syntax().last_token() {
Some(last_token) => last_token,
None => return node,
};
if let Some(sep) = sep {
if is_last && separator_count == last_element {
// If this is the last item and we are removing its trailing separator,
// move the trailing trivia from the separator to the node
let next_token =
prev_token.append_trivia_pieces(sep.trailing_trivia().pieces());
node = node
.replace_token_discard_trivia(prev_token, next_token)
.expect("prev_token should be a child of node");
}
} else if !is_last {
// If the node has no separator and this is not the last item,
// remove the trailing trivia since it will get cloned on the inserted separator
let next_token = prev_token.with_trailing_trivia([]);
node = node
.replace_token_discard_trivia(prev_token, next_token)
.expect("prev_token should be a child of node");
}
// Check if the last separator we emitted ended with a single-line comment
if let Some(newline_source) = needs_newline.take() {
if let Some(first_token) = node.syntax().first_token() {
if let Some(new_token) =
prepend_leading_newline(&first_token, newline_source)
{
node = node
.replace_token_discard_trivia(first_token, new_token)
.expect("first_token should be a child of node");
}
}
}
node
});
let separators = self
.specifiers
.values()
.take(separator_count)
.map(|(node, sep)| {
// If this entry has an associated separator, reuse it
let (token, will_need_newline) = if let Some(sep) = sep {
// If the last trivia piece for the separator token is a single-line comment,
// signal to the items iterator it will need to prepend a newline to the leading
// trivia of the next node
let will_need_newline = sep
.trailing_trivia()
.last()
.map(|piece| piece.kind().is_single_line_comment())
.unwrap_or(false);
(sep.clone(), will_need_newline)
} else {
// If the node we're attaching this separator to has no trailing trivia, just create a simple comma token
let last_trailing_trivia = match node.syntax().last_trailing_trivia() {
Some(trivia) if !trivia.is_empty() => trivia,
_ => return make::token(T![,]),
};
// Otherwise we need to clone the trailing trivia from the node to the separator
// (the items iterator should have already filtered this trivia when it previously
// emitted the node)
let mut text = String::from(",");
let mut trailing = Vec::with_capacity(last_trailing_trivia.pieces().len());
let mut will_need_newline = false;
for piece in last_trailing_trivia.pieces() {
text.push_str(piece.text());
trailing.push(TriviaPiece::new(piece.kind(), piece.text_len()));
will_need_newline =
matches!(piece.kind(), TriviaPieceKind::SingleLineComment);
}
let token = JsSyntaxToken::new_detached(T![,], &text, [], trailing);
(token, will_need_newline)
};
// If the last trivia piece was a single-line comment, signal to the items iterator
// it will need to prepend a newline to the leading trivia of the next node, and provide
// it the token that followed this separator in the original source so the newline trivia
// can be cloned from there
let newline_source =
will_need_newline.then(|| sep.as_ref().and_then(|token| token.next_token()));
needs_newline.set(newline_source);
token
});
let mut new_specifiers = old_specifiers
.clone()
.detach()
.with_specifiers(make::js_named_import_specifier_list(items, separators));
// If the separators iterator has a pending newline, prepend it to closing curly token
if let Some(newline_source) = needs_newline.into_inner() {
let new_token = new_specifiers
.r_curly_token()
.ok()
.and_then(|token| prepend_leading_newline(&token, newline_source));
if let Some(new_token) = new_token {
new_specifiers = new_specifiers.with_r_curly_token(new_token);
}
}
import
.replace_node_discard_trivia(old_specifiers, new_specifiers)
.expect("old_specifiers should be a child of import")
}
}
/// Return the name associated with a given named import specifier
///
/// Currently named import specifiers are sorted using their import name,
/// not the local name they get imported as
fn import_specifier_name(import_specifier: &AnyJsNamedImportSpecifier) -> Option<TokenText> {
let token = match import_specifier {
AnyJsNamedImportSpecifier::JsNamedImportSpecifier(import_specifier) => {
import_specifier.name().ok()?.value().ok()?
}
AnyJsNamedImportSpecifier::JsShorthandNamedImportSpecifier(import_specifier) => {
import_specifier
.local_name()
.ok()?
.as_js_identifier_binding()?
.name_token()
.ok()?
}
AnyJsNamedImportSpecifier::JsBogusNamedImportSpecifier(_) => return None,
};
Some(token.token_text_trimmed())
}
/// Return a clone of `prev_token` with a newline trivia piece prepended to its
/// leading trivia if it didn't have one already. This function will try to copy
/// the newline trivia piece from the leading trivia of `newline_source` if its set
fn prepend_leading_newline(
prev_token: &JsSyntaxToken,
newline_source: Option<JsSyntaxToken>,
) -> Option<JsSyntaxToken> {
// Check if this node already starts with a newline,
// if it does we don't need to prepend anything
let leading_trivia = prev_token.leading_trivia();
let has_leading_newline = leading_trivia
.first()
.map(|piece| piece.is_newline())
.unwrap_or(false);
if has_leading_newline {
return None;
}
// Extract the leading newline from the `newline_source` token
let leading_newline = newline_source.and_then(|newline_source| {
let leading_piece = newline_source.leading_trivia().first()?;
if !leading_piece.is_newline() {
return None;
}
Some(leading_piece)
});
// Prepend a newline trivia piece to the node, either by copying the leading newline
// and whitespace from `newline_source`, or falling back to the "\n" character
let leading_newline = if let Some(leading_newline) = &leading_newline {
(leading_newline.kind(), leading_newline.text())
} else {
(TriviaPieceKind::Newline, "\n")
};
let piece_count = 1 + leading_trivia.pieces().len();
let mut iter = iter::once(leading_newline).chain(leading_trivia_iter(prev_token));
Some(prev_token.with_leading_trivia((0..piece_count).map(|_| iter.next().unwrap())))
}
/// Builds an iterator over the leading trivia pieces of a token
///
/// The items of the iterator inherit their lifetime from the token,
/// rather than the trivia pieces themselves
fn leading_trivia_iter(
token: &JsSyntaxToken,
) -> impl ExactSizeIterator<Item = (TriviaPieceKind, &str)> {
let token_text = token.text();
let token_range = token.text_range();
let trivia = token.leading_trivia();
trivia.pieces().map(move |piece| {
let piece_range = piece.text_range();
let range = TextRange::at(piece_range.start() - token_range.start(), piece_range.len());
let text = &token_text[range];
assert_eq!(text, piece.text());
(piece.kind(), text)
})
}
#[derive(Debug)]
struct ImportKey(TokenText);
impl Ord for ImportKey {
fn cmp(&self, other: &Self) -> Ordering {
let own_category = ImportCategory::from(self.0.text());
let other_category = ImportCategory::from(other.0.text());
if own_category != other_category {
return own_category.cmp(&other_category);
}
// Sort imports using natural ordering
natord::compare(&self.0, &other.0)
}
}
impl PartialOrd for ImportKey {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for ImportKey {}
impl PartialEq for ImportKey {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
/// Imports get sorted by categories before being sorted on natural order.
///
/// The rationale for this is that imports "further away" from the source file
/// are listed before imports closer to the source file.
#[derive(Eq, Ord, PartialEq, PartialOrd)]
enum ImportCategory {
/// Anything with an explicit `node:` prefix, or one of the recognized
/// Node built-ins, such `"fs"`, `"child_process"`, etc..
NodeBuiltin,
/// NPM dependencies with an explicit `npm:` prefix, such as supported by
/// Deno.
Npm,
/// Imports from an absolute URL such as supported by browsers.
Url,
/// Anything without explicit protocol specifier is assumed to be a library
/// import. Because we currently do not have configuration for this, this
/// may (incorrectly) include source imports through custom import mappings
/// as well.
Library,
/// Relative file imports.
Relative,
/// Any unrecognized protocols are grouped here. These may include custom
/// protocols such as supported by bundlers.
Other,
}
const NODE_BUILTINS: &[&str] = &[
"assert",
"buffer",
"child_process",
"cluster",
"console",
"constants",
"crypto",
"dgram",
"dns",
"domain",
"events",
"fs",
"http",
"https",
"module",
"net",
"os",
"path",
"punycode",
"querystring",
"readline",
"repl",
"stream",
"string_decoder",
"sys",
"timers",
"tls",
"tty",
"url",
"util",
"vm",
"zlib",
];
impl From<&str> for ImportCategory {
fn from(value: &str) -> Self {
if value.starts_with("node:") || NODE_BUILTINS.contains(&value) {
Self::NodeBuiltin
} else if value.starts_with("npm:") {
Self::Npm
} else if value.starts_with("http:") || value.starts_with("https:") {
Self::Url
} else if value.starts_with('.') {
Self::Relative
} else if !value.contains(':') {
Self::Library
} else {
Self::Other
}
}
}
/// Returns true is this trivia piece is "ASCII whitespace" (newline or whitespace)
fn is_ascii_whitespace(piece: &SyntaxTriviaPiece<JsLanguage>) -> bool {
piece.is_newline() || piece.is_whitespace()
}
/// Returns true if the provided trivia contains an empty line (two consecutive newline pieces, ignoring whitespace)
fn has_empty_line(trivia: SyntaxTrivia<JsLanguage>) -> bool {
let mut was_newline = false;
trivia
.pieces()
.filter(|piece| !piece.is_whitespace())
.any(|piece| {
let prev_newline = was_newline;
was_newline = piece.is_newline();
prev_newline && was_newline
})
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/assists/correctness/inline_variable.rs | crates/rome_js_analyze/src/assists/correctness/inline_variable.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, RefactorKind, Rule};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_semantic::{Reference, ReferencesExtensions};
use rome_js_syntax::{
AnyJsBinding, AnyJsBindingPattern, AnyJsExpression, JsIdentifierExpression,
JsVariableDeclarator,
};
use rome_rowan::{BatchMutationExt, SyntaxNodeCast};
use crate::{semantic_services::Semantic, utils::remove_declarator, JsRuleAction};
declare_rule! {
/// Provides a refactor to inline variables
///
/// ## Examples
///
/// ```js
/// let variable = expression();
/// statement(variable);
/// ```
pub(crate) InlineVariable {
version: "0.9.0",
name: "inlineVariable",
recommended: false,
}
}
/// Signal struct emitted for each variable declaration the rule can inline
pub(crate) struct State {
/// List of references to the variable
references: Vec<Reference>,
/// Initializer expression for the variable to be inlined
expression: AnyJsExpression,
}
impl Rule for InlineVariable {
type Query = Semantic<JsVariableDeclarator>;
type State = State;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let semantic_model = ctx.model();
let declarator = ctx.query();
let id = declarator.id().ok()?;
let binding = match id {
AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(binding)) => {
binding
}
AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsBogusBinding(_))
| AnyJsBindingPattern::JsArrayBindingPattern(_)
| AnyJsBindingPattern::JsObjectBindingPattern(_) => return None,
};
// Do not inline if the initializer is not inlinable
let initializer = declarator.initializer()?;
let expr = initializer.expression().ok()?;
match expr {
AnyJsExpression::JsArrowFunctionExpression(_)
| AnyJsExpression::JsFunctionExpression(_)
| AnyJsExpression::JsClassExpression(_)
| AnyJsExpression::JsAssignmentExpression(_) => return None,
_ => {}
}
// Do not inline if there is a write
let mut references = Vec::new();
for reference in binding.all_references(semantic_model) {
if reference.is_write() {
return None;
}
references.push(reference);
}
// Inline variable
let expression = initializer.expression().ok()?;
Some(State {
references,
expression,
})
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let State {
references,
expression,
} = state;
remove_declarator(&mut mutation, node);
for reference in references {
let node = reference
.syntax()
.parent()?
.cast::<JsIdentifierExpression>()?;
mutation.replace_node(
AnyJsExpression::JsIdentifierExpression(node),
expression.clone(),
);
}
Some(JsRuleAction {
category: ActionCategory::Refactor(RefactorKind::Inline),
applicability: Applicability::Always,
message: markup! { "Inline variable" }.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/globals/node.rs | crates/rome_js_analyze/src/globals/node.rs | pub const BUILTIN: [&str; 29] = [
"AbortController",
"AbortSignal",
"Buffer",
"DOMException",
"Event",
"EventTarget",
"Intl",
"MessageChannel",
"MessageEvent",
"MessagePort",
"TextDecoder",
"TextEncoder",
"URL",
"URLSearchParams",
"atob",
"btoa",
"clearImmediate",
"clearInterval",
"clearTimeout",
"console",
"fetch",
"global",
"performance",
"process",
"queueMicrotask",
"setImmediate",
"setInterval",
"setTimeout",
"structuredClone",
];
pub const NODE: [&str; 34] = [
"AbortController",
"AbortSignal",
"Buffer",
"DOMException",
"Event",
"EventTarget",
"Intl",
"MessageChannel",
"MessageEvent",
"MessagePort",
"TextDecoder",
"TextEncoder",
"URL",
"URLSearchParams",
"__dirname",
"__filename",
"atob",
"btoa",
"clearImmediate",
"clearInterval",
"clearTimeout",
"console",
"exports",
"fetch",
"global",
"module",
"performance",
"process",
"queueMicrotask",
"require",
"setImmediate",
"setInterval",
"setTimeout",
"structuredClone",
];
pub const COMMON_JS: [&str; 4] = ["exports", "global", "module", "require"];
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/globals/typescript.rs | crates/rome_js_analyze/src/globals/typescript.rs | pub const TYPESCRIPT_BUILTIN: [&str; 140] = [
"AggregateErrorConstructor",
"ArrayBufferConstructor",
"ArrayBufferLike",
"ArrayBufferTypes",
"ArrayBufferView",
"ArrayConstructor",
"ArrayLike",
"AsyncDisposable",
"AsyncDisposableStack",
"AsyncDisposableStackConstructor",
"AsyncGenerator",
"AsyncGeneratorFunction",
"AsyncGeneratorFunctionConstructor",
"AsyncIterable",
"AsyncIterableIterator",
"AsyncIterator",
"Atomics",
"Awaited",
"BigInt64ArrayConstructor",
"BigIntConstructor",
"BigIntToLocaleStringOptions",
"BigUint64ArrayConstructor",
"BooleanConstructor",
"BufferEncoding",
"BufferSource",
"CallableFunction",
"Capitalize",
"ClassAccessorDecoratorContext",
"ClassAccessorDecoratorResult",
"ClassAccessorDecoratorTarget",
"ClassDecorator",
"ClassDecoratorContext",
"ClassFieldDecoratorContext",
"ClassGetterDecoratorContext",
"ClassMemberDecoratorContext",
"ClassMethodDecoratorContext",
"ClassSetterDecoratorContext",
"ConcatArray",
"Console",
"ConstructorParameters",
"DataViewConstructor",
"DateConstructor",
"DecoratorContext",
"DecoratorMetadata",
"DecoratorMetadataObject",
"Disposable",
"DisposableStack",
"DisposableStackConstructor",
"ErrorConstructor",
"ErrorOptions",
"EvalErrorConstructor",
"Exclude",
"Extract",
"FinalizationRegistryConstructor",
"FlatArray",
"Float32ArrayConstructor",
"Float64ArrayConstructor",
"FunctionConstructor",
"Generator",
"GeneratorFunction",
"GeneratorFunctionConstructor",
"IArguments",
"ImportAssertions",
"ImportCallOptions",
"ImportMeta",
"InstanceType",
"Int16ArrayConstructor",
"Int32ArrayConstructor",
"Int8ArrayConstructor",
"Iterable",
"IterableIterator",
"Iterator",
"IteratorResult",
"IteratorReturnResult",
"IteratorYieldResult",
"Lowercase",
"MapConstructor",
"MethodDecorator",
"NewableFunction",
"NodeJS",
"NodeRequire",
"NonNullable",
"NumberConstructor",
"ObjectConstructor",
"Omit",
"OmitThisParameter",
"ParameterDecorator",
"Parameters",
"Partial",
"Pick",
"PromiseConstructor",
"PromiseConstructorLike",
"PromiseFulfilledResult",
"PromiseLike",
"PromiseRejectedResult",
"PromiseSettledResult",
"PropertyDecorator",
"PropertyDescriptor",
"PropertyDescriptorMap",
"PropertyKey",
"ProxyConstructor",
"ProxyHandler",
"RangeErrorConstructor",
"Readonly",
"ReadonlyArray",
"ReadonlyMap",
"ReadonlySet",
"Record",
"ReferenceErrorConstructor",
"RegExpConstructor",
"RegExpExecArray",
"RegExpIndicesArray",
"RegExpMatchArray",
"RequestInit",
"Required",
"ReturnType",
"SetConstructor",
"SharedArrayBufferConstructor",
"StringConstructor",
"SuppressedErrorConstructor",
"SymbolConstructor",
"SyntaxErrorConstructor",
"TemplateStringsArray",
"Thenable",
"ThisParameterType",
"ThisType",
"TypedPropertyDescriptor",
"TypeErrorConstructor",
"Uint16ArrayConstructor",
"Uint32ArrayConstructor",
"Uint8ArrayConstructor",
"Uint8ClampedArrayConstructor",
"Uncapitalize",
"Uppercase",
"URIErrorConstructor",
"WeakKey",
"WeakKeyTypes",
"WeakMapConstructor",
"WeakRefConstructor",
"WeakSetConstructor",
];
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/globals/browser.rs | crates/rome_js_analyze/src/globals/browser.rs | pub const BROWSER: [&str; 706] = [
"AbortController",
"AbortSignal",
"AnalyserNode",
"Animation",
"AnimationEffectReadOnly",
"AnimationEffectTiming",
"AnimationEffectTimingReadOnly",
"AnimationEvent",
"AnimationPlaybackEvent",
"AnimationTimeline",
"ApplicationCache",
"ApplicationCacheErrorEvent",
"Attr",
"Audio",
"AudioBuffer",
"AudioBufferSourceNode",
"AudioContext",
"AudioDestinationNode",
"AudioListener",
"AudioNode",
"AudioParam",
"AudioProcessingEvent",
"AudioScheduledSourceNode",
"AudioWorkletGlobalScope ",
"AudioWorkletNode",
"AudioWorkletProcessor",
"BarProp",
"BaseAudioContext",
"BatteryManager",
"BeforeUnloadEvent",
"BiquadFilterNode",
"Blob",
"BlobEvent",
"BroadcastChannel",
"BudgetService",
"ByteLengthQueuingStrategy",
"CSS",
"CSSConditionRule",
"CSSFontFaceRule",
"CSSGroupingRule",
"CSSImportRule",
"CSSKeyframeRule",
"CSSKeyframesRule",
"CSSMediaRule",
"CSSNamespaceRule",
"CSSPageRule",
"CSSRule",
"CSSRuleList",
"CSSStyleDeclaration",
"CSSStyleRule",
"CSSStyleSheet",
"CSSSupportsRule",
"Cache",
"CacheStorage",
"CanvasCaptureMediaStreamTrack",
"CanvasGradient",
"CanvasPattern",
"CanvasRenderingContext2D",
"ChannelMergerNode",
"ChannelSplitterNode",
"CharacterData",
"ClipboardEvent",
"CloseEvent",
"Comment",
"CompositionEvent",
"ConstantSourceNode",
"ConvolverNode",
"CountQueuingStrategy",
"Credential",
"CredentialsContainer",
"Crypto",
"CryptoKey",
"CustomElementRegistry",
"CustomEvent",
"DOMError",
"DOMException",
"DOMImplementation",
"DOMMatrix",
"DOMMatrixReadOnly",
"DOMParser",
"DOMPoint",
"DOMPointReadOnly",
"DOMQuad",
"DOMRect",
"DOMRectReadOnly",
"DOMStringList",
"DOMStringMap",
"DOMTokenList",
"DataTransfer",
"DataTransferItem",
"DataTransferItemList",
"DelayNode",
"DeviceMotionEvent",
"DeviceOrientationEvent",
"Document",
"DocumentFragment",
"DocumentType",
"DragEvent",
"DynamicsCompressorNode",
"Element",
"ErrorEvent",
"Event",
"EventSource",
"EventTarget",
"File",
"FileList",
"FileReader",
"FocusEvent",
"FontFace",
"FontFaceSetLoadEvent",
"FormData",
"GainNode",
"Gamepad",
"GamepadButton",
"GamepadEvent",
"HTMLAllCollection",
"HTMLAnchorElement",
"HTMLAreaElement",
"HTMLAudioElement",
"HTMLBRElement",
"HTMLBaseElement",
"HTMLBodyElement",
"HTMLButtonElement",
"HTMLCanvasElement",
"HTMLCollection",
"HTMLContentElement",
"HTMLDListElement",
"HTMLDataElement",
"HTMLDataListElement",
"HTMLDetailsElement",
"HTMLDialogElement",
"HTMLDirectoryElement",
"HTMLDivElement",
"HTMLDocument",
"HTMLElement",
"HTMLEmbedElement",
"HTMLFieldSetElement",
"HTMLFontElement",
"HTMLFormControlsCollection",
"HTMLFormElement",
"HTMLFrameElement",
"HTMLFrameSetElement",
"HTMLHRElement",
"HTMLHeadElement",
"HTMLHeadingElement",
"HTMLHtmlElement",
"HTMLIFrameElement",
"HTMLImageElement",
"HTMLInputElement",
"HTMLLIElement",
"HTMLLabelElement",
"HTMLLegendElement",
"HTMLLinkElement",
"HTMLMapElement",
"HTMLMarqueeElement",
"HTMLMediaElement",
"HTMLMenuElement",
"HTMLMetaElement",
"HTMLMeterElement",
"HTMLModElement",
"HTMLOListElement",
"HTMLObjectElement",
"HTMLOptGroupElement",
"HTMLOptionElement",
"HTMLOptionsCollection",
"HTMLOutputElement",
"HTMLParagraphElement",
"HTMLParamElement",
"HTMLPictureElement",
"HTMLPreElement",
"HTMLProgressElement",
"HTMLQuoteElement",
"HTMLScriptElement",
"HTMLSelectElement",
"HTMLShadowElement",
"HTMLSlotElement",
"HTMLSourceElement",
"HTMLSpanElement",
"HTMLStyleElement",
"HTMLTableCaptionElement",
"HTMLTableCellElement",
"HTMLTableColElement",
"HTMLTableElement",
"HTMLTableRowElement",
"HTMLTableSectionElement",
"HTMLTemplateElement",
"HTMLTextAreaElement",
"HTMLTimeElement",
"HTMLTitleElement",
"HTMLTrackElement",
"HTMLUListElement",
"HTMLUnknownElement",
"HTMLVideoElement",
"HashChangeEvent",
"Headers",
"History",
"IDBCursor",
"IDBCursorWithValue",
"IDBDatabase",
"IDBFactory",
"IDBIndex",
"IDBKeyRange",
"IDBObjectStore",
"IDBOpenDBRequest",
"IDBRequest",
"IDBTransaction",
"IDBVersionChangeEvent",
"IIRFilterNode",
"IdleDeadline",
"Image",
"ImageBitmap",
"ImageBitmapRenderingContext",
"ImageCapture",
"ImageData",
"InputEvent",
"IntersectionObserver",
"IntersectionObserverEntry",
"Intl",
"KeyboardEvent",
"KeyframeEffect",
"KeyframeEffectReadOnly",
"Location",
"MIDIAccess",
"MIDIConnectionEvent",
"MIDIInput",
"MIDIInputMap",
"MIDIMessageEvent",
"MIDIOutput",
"MIDIOutputMap",
"MIDIPort",
"MediaDeviceInfo",
"MediaDevices",
"MediaElementAudioSourceNode",
"MediaEncryptedEvent",
"MediaError",
"MediaKeyMessageEvent",
"MediaKeySession",
"MediaKeyStatusMap",
"MediaKeySystemAccess",
"MediaList",
"MediaQueryList",
"MediaQueryListEvent",
"MediaRecorder",
"MediaSettingsRange",
"MediaSource",
"MediaStream",
"MediaStreamAudioDestinationNode",
"MediaStreamAudioSourceNode",
"MediaStreamEvent",
"MediaStreamTrack",
"MediaStreamTrackEvent",
"MessageChannel",
"MessageEvent",
"MessagePort",
"MimeType",
"MimeTypeArray",
"MouseEvent",
"MutationEvent",
"MutationObserver",
"MutationRecord",
"NamedNodeMap",
"NavigationPreloadManager",
"Navigator",
"NetworkInformation",
"Node",
"NodeFilter",
"NodeIterator",
"NodeList",
"Notification",
"OfflineAudioCompletionEvent",
"OfflineAudioContext",
"OffscreenCanvas",
"OffscreenCanvasRenderingContext2D",
"Option",
"OscillatorNode",
"PageTransitionEvent",
"PannerNode",
"Path2D",
"PaymentAddress",
"PaymentRequest",
"PaymentRequestUpdateEvent",
"PaymentResponse",
"Performance",
"PerformanceEntry",
"PerformanceLongTaskTiming",
"PerformanceMark",
"PerformanceMeasure",
"PerformanceNavigation",
"PerformanceNavigationTiming",
"PerformanceObserver",
"PerformanceObserverEntryList",
"PerformancePaintTiming",
"PerformanceResourceTiming",
"PerformanceTiming",
"PeriodicWave",
"PermissionStatus",
"Permissions",
"PhotoCapabilities",
"Plugin",
"PluginArray",
"PointerEvent",
"PopStateEvent",
"Presentation",
"PresentationAvailability",
"PresentationConnection",
"PresentationConnectionAvailableEvent",
"PresentationConnectionCloseEvent",
"PresentationConnectionList",
"PresentationReceiver",
"PresentationRequest",
"ProcessingInstruction",
"ProgressEvent",
"PromiseRejectionEvent",
"PushManager",
"PushSubscription",
"PushSubscriptionOptions",
"RTCCertificate",
"RTCDataChannel",
"RTCDataChannelEvent",
"RTCDtlsTransport",
"RTCIceCandidate",
"RTCIceGatherer",
"RTCIceTransport",
"RTCPeerConnection",
"RTCPeerConnectionIceEvent",
"RTCRtpContributingSource",
"RTCRtpReceiver",
"RTCRtpSender",
"RTCSctpTransport",
"RTCSessionDescription",
"RTCStatsReport",
"RTCTrackEvent",
"RadioNodeList",
"Range",
"ReadableStream",
"RemotePlayback",
"Request",
"ResizeObserver",
"ResizeObserverEntry",
"Response",
"SVGAElement",
"SVGAngle",
"SVGAnimateElement",
"SVGAnimateMotionElement",
"SVGAnimateTransformElement",
"SVGAnimatedAngle",
"SVGAnimatedBoolean",
"SVGAnimatedEnumeration",
"SVGAnimatedInteger",
"SVGAnimatedLength",
"SVGAnimatedLengthList",
"SVGAnimatedNumber",
"SVGAnimatedNumberList",
"SVGAnimatedPreserveAspectRatio",
"SVGAnimatedRect",
"SVGAnimatedString",
"SVGAnimatedTransformList",
"SVGAnimationElement",
"SVGCircleElement",
"SVGClipPathElement",
"SVGComponentTransferFunctionElement",
"SVGDefsElement",
"SVGDescElement",
"SVGDiscardElement",
"SVGElement",
"SVGEllipseElement",
"SVGFEBlendElement",
"SVGFEColorMatrixElement",
"SVGFEComponentTransferElement",
"SVGFECompositeElement",
"SVGFEConvolveMatrixElement",
"SVGFEDiffuseLightingElement",
"SVGFEDisplacementMapElement",
"SVGFEDistantLightElement",
"SVGFEDropShadowElement",
"SVGFEFloodElement",
"SVGFEFuncAElement",
"SVGFEFuncBElement",
"SVGFEFuncGElement",
"SVGFEFuncRElement",
"SVGFEGaussianBlurElement",
"SVGFEImageElement",
"SVGFEMergeElement",
"SVGFEMergeNodeElement",
"SVGFEMorphologyElement",
"SVGFEOffsetElement",
"SVGFEPointLightElement",
"SVGFESpecularLightingElement",
"SVGFESpotLightElement",
"SVGFETileElement",
"SVGFETurbulenceElement",
"SVGFilterElement",
"SVGForeignObjectElement",
"SVGGElement",
"SVGGeometryElement",
"SVGGradientElement",
"SVGGraphicsElement",
"SVGImageElement",
"SVGLength",
"SVGLengthList",
"SVGLineElement",
"SVGLinearGradientElement",
"SVGMPathElement",
"SVGMarkerElement",
"SVGMaskElement",
"SVGMatrix",
"SVGMetadataElement",
"SVGNumber",
"SVGNumberList",
"SVGPathElement",
"SVGPatternElement",
"SVGPoint",
"SVGPointList",
"SVGPolygonElement",
"SVGPolylineElement",
"SVGPreserveAspectRatio",
"SVGRadialGradientElement",
"SVGRect",
"SVGRectElement",
"SVGSVGElement",
"SVGScriptElement",
"SVGSetElement",
"SVGStopElement",
"SVGStringList",
"SVGStyleElement",
"SVGSwitchElement",
"SVGSymbolElement",
"SVGTSpanElement",
"SVGTextContentElement",
"SVGTextElement",
"SVGTextPathElement",
"SVGTextPositioningElement",
"SVGTitleElement",
"SVGTransform",
"SVGTransformList",
"SVGUnitTypes",
"SVGUseElement",
"SVGViewElement",
"Screen",
"ScreenOrientation",
"ScriptProcessorNode",
"SecurityPolicyViolationEvent",
"Selection",
"ServiceWorker",
"ServiceWorkerContainer",
"ServiceWorkerRegistration",
"ShadowRoot",
"SharedWorker",
"SourceBuffer",
"SourceBufferList",
"SpeechSynthesisEvent",
"SpeechSynthesisUtterance",
"StaticRange",
"StereoPannerNode",
"Storage",
"StorageEvent",
"StorageManager",
"StyleSheet",
"StyleSheetList",
"SubtleCrypto",
"TaskAttributionTiming",
"Text",
"TextDecoder",
"TextEncoder",
"TextEvent",
"TextMetrics",
"TextTrack",
"TextTrackCue",
"TextTrackCueList",
"TextTrackList",
"TimeRanges",
"Touch",
"TouchEvent",
"TouchList",
"TrackEvent",
"TransitionEvent",
"TreeWalker",
"UIEvent",
"URL",
"URLSearchParams",
"VTTCue",
"ValidityState",
"VisualViewport",
"WaveShaperNode",
"WebAssembly",
"WebGL2RenderingContext",
"WebGLActiveInfo",
"WebGLBuffer",
"WebGLContextEvent",
"WebGLFramebuffer",
"WebGLProgram",
"WebGLQuery",
"WebGLRenderbuffer",
"WebGLRenderingContext",
"WebGLSampler",
"WebGLShader",
"WebGLShaderPrecisionFormat",
"WebGLSync",
"WebGLTexture",
"WebGLTransformFeedback",
"WebGLUniformLocation",
"WebGLVertexArrayObject",
"WebSocket",
"WheelEvent",
"Window",
"Worker",
"WritableStream",
"XMLDocument",
"XMLHttpRequest",
"XMLHttpRequestEventTarget",
"XMLHttpRequestUpload",
"XMLSerializer",
"XPathEvaluator",
"XPathExpression",
"XPathResult",
"XSLTProcessor",
"addEventListener",
"alert",
"applicationCache",
"atob",
"blur",
"btoa",
"caches",
"cancelAnimationFrame",
"cancelIdleCallback",
"clearInterval",
"clearTimeout",
"clientInformation",
"close",
"closed",
"confirm",
"console",
"createImageBitmap",
"crypto",
"customElements",
"defaultStatus",
"defaultstatus",
"devicePixelRatio",
"dispatchEvent",
"document",
"event",
"external",
"fetch",
"find",
"focus",
"frameElement",
"frames",
"getComputedStyle",
"getSelection",
"history",
"indexedDB",
"innerHeight",
"innerWidth",
"isSecureContext",
"length",
"localStorage",
"location",
"locationbar",
"matchMedia",
"menubar",
"moveBy",
"moveTo",
"name",
"navigator",
"offscreenBuffering",
"onabort",
"onafterprint",
"onanimationend",
"onanimationiteration",
"onanimationstart",
"onappinstalled",
"onauxclick",
"onbeforeinstallprompt",
"onbeforeprint",
"onbeforeunload",
"onblur",
"oncancel",
"oncanplay",
"oncanplaythrough",
"onchange",
"onclick",
"onclose",
"oncontextmenu",
"oncuechange",
"ondblclick",
"ondevicemotion",
"ondeviceorientation",
"ondeviceorientationabsolute",
"ondrag",
"ondragend",
"ondragenter",
"ondragleave",
"ondragover",
"ondragstart",
"ondrop",
"ondurationchange",
"onemptied",
"onended",
"onerror",
"onfocus",
"ongotpointercapture",
"onhashchange",
"oninput",
"oninvalid",
"onkeydown",
"onkeypress",
"onkeyup",
"onlanguagechange",
"onload",
"onloadeddata",
"onloadedmetadata",
"onloadstart",
"onlostpointercapture",
"onmessage",
"onmessageerror",
"onmousedown",
"onmouseenter",
"onmouseleave",
"onmousemove",
"onmouseout",
"onmouseover",
"onmouseup",
"onmousewheel",
"onoffline",
"ononline",
"onpagehide",
"onpageshow",
"onpause",
"onplay",
"onplaying",
"onpointercancel",
"onpointerdown",
"onpointerenter",
"onpointerleave",
"onpointermove",
"onpointerout",
"onpointerover",
"onpointerup",
"onpopstate",
"onprogress",
"onratechange",
"onrejectionhandled",
"onreset",
"onresize",
"onscroll",
"onsearch",
"onseeked",
"onseeking",
"onselect",
"onstalled",
"onstorage",
"onsubmit",
"onsuspend",
"ontimeupdate",
"ontoggle",
"ontransitionend",
"onunhandledrejection",
"onunload",
"onvolumechange",
"onwaiting",
"onwheel",
"open",
"openDatabase",
"opener",
"origin",
"outerHeight",
"outerWidth",
"pageXOffset",
"pageYOffset",
"parent",
"performance",
"personalbar",
"postMessage",
"print",
"prompt",
"queueMicrotask",
"registerProcessor",
"removeEventListener",
"requestAnimationFrame",
"requestIdleCallback",
"resizeBy",
"resizeTo",
"screen",
"screenLeft",
"screenTop",
"screenX",
"screenY",
"scroll",
"scrollBy",
"scrollTo",
"scrollX",
"scrollY",
"scrollbars",
"self",
"sessionStorage",
"setInterval",
"setTimeout",
"speechSynthesis",
"status",
"statusbar",
"stop",
"styleMedia",
"toolbar",
"top",
"visualViewport",
"window",
];
pub const SERVICE_WORKER: [&str; 93] = [
"Blob",
"BroadcastChannel",
"Cache",
"CacheStorage",
"Client",
"Clients",
"ExtendableEvent",
"ExtendableMessageEvent",
"FetchEvent",
"FileReaderSync",
"FormData",
"Headers",
"IDBCursor",
"IDBCursorWithValue",
"IDBDatabase",
"IDBFactory",
"IDBIndex",
"IDBKeyRange",
"IDBObjectStore",
"IDBOpenDBRequest",
"IDBRequest",
"IDBTransaction",
"IDBVersionChangeEvent",
"ImageData",
"MessageChannel",
"MessagePort",
"Notification",
"Performance",
"PerformanceEntry",
"PerformanceMark",
"PerformanceMeasure",
"PerformanceNavigation",
"PerformanceResourceTiming",
"PerformanceTiming",
"Promise",
"Request",
"Response",
"ServiceWorker",
"ServiceWorkerContainer",
"ServiceWorkerGlobalScope",
"ServiceWorkerMessageEvent",
"ServiceWorkerRegistration",
"TextDecoder",
"TextEncoder",
"URL",
"URLSearchParams",
"WebSocket",
"WindowClient",
"Worker",
"WorkerGlobalScope",
"XMLHttpRequest",
"addEventListener",
"applicationCache",
"atob",
"btoa",
"caches",
"clearInterval",
"clearTimeout",
"clients",
"close",
"console",
"fetch",
"importScripts",
"indexedDB",
"location",
"name",
"navigator",
"onclose",
"onconnect",
"onerror",
"onfetch",
"oninstall",
"onlanguagechange",
"onmessage",
"onmessageerror",
"onnotificationclick",
"onnotificationclose",
"onoffline",
"ononline",
"onpush",
"onpushsubscriptionchange",
"onrejectionhandled",
"onsync",
"onunhandledrejection",
"performance",
"postMessage",
"queueMicrotask",
"registration",
"removeEventListener",
"self",
"setInterval",
"setTimeout",
"skipWaiting",
];
pub const WORKER: [&str; 71] = [
"Blob",
"BroadcastChannel",
"Cache",
"FileReaderSync",
"FormData",
"Headers",
"IDBCursor",
"IDBCursorWithValue",
"IDBDatabase",
"IDBFactory",
"IDBIndex",
"IDBKeyRange",
"IDBObjectStore",
"IDBOpenDBRequest",
"IDBRequest",
"IDBTransaction",
"IDBVersionChangeEvent",
"ImageData",
"MessageChannel",
"MessagePort",
"Notification",
"Performance",
"PerformanceEntry",
"PerformanceMark",
"PerformanceMeasure",
"PerformanceNavigation",
"PerformanceResourceTiming",
"PerformanceTiming",
"Promise",
"Request",
"Response",
"ServiceWorkerRegistration",
"TextDecoder",
"TextEncoder",
"URL",
"URLSearchParams",
"WebSocket",
"Worker",
"WorkerGlobalScope",
"XMLHttpRequest",
"addEventListener",
"applicationCache",
"atob",
"btoa",
"caches",
"clearInterval",
"clearTimeout",
"close",
"console",
"fetch",
"importScripts",
"indexedDB",
"location",
"name",
"navigator",
"onclose",
"onconnect",
"onerror",
"onlanguagechange",
"onmessage",
"onoffline",
"ononline",
"onrejectionhandled",
"onunhandledrejection",
"performance",
"postMessage",
"queueMicrotask",
"removeEventListener",
"self",
"setInterval",
"setTimeout",
];
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/globals/runtime.rs | crates/rome_js_analyze/src/globals/runtime.rs | pub const BUILTIN: [&str; 66] = [
"AggregateError",
"Array",
"ArrayBuffer",
"Atomics",
"BigInt",
"BigInt64Array",
"BigUint64Array",
"Boolean",
"DataView",
"Date",
"Error",
"EvalError",
"FinalizationRegistry",
"Float32Array",
"Float64Array",
"Function",
"Infinity",
"Int16Array",
"Int32Array",
"Int8Array",
"JSON",
"Map",
"Math",
"NaN",
"Number",
"Object",
"Promise",
"Proxy",
"RangeError",
"ReferenceError",
"Reflect",
"RegExp",
"Set",
"SharedArrayBuffer",
"String",
"Symbol",
"SyntaxError",
"TypeError",
"URIError",
"Uint16Array",
"Uint32Array",
"Uint8Array",
"Uint8ClampedArray",
"WeakMap",
"WeakRef",
"WeakSet",
"constructor",
"decodeURI",
"decodeURIComponent",
"encodeURI",
"encodeURIComponent",
"escape",
"eval",
"globalThis",
"hasOwnProperty",
"isFinite",
"isNaN",
"isPrototypeOf",
"parseFloat",
"parseInt",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"undefined",
"unescape",
"valueOf",
];
pub const ES_5: [&str; 38] = [
"Array",
"Boolean",
"Date",
"Error",
"EvalError",
"Function",
"Infinity",
"JSON",
"Math",
"NaN",
"Number",
"Object",
"RangeError",
"ReferenceError",
"RegExp",
"String",
"SyntaxError",
"TypeError",
"URIError",
"constructor",
"decodeURI",
"decodeURIComponent",
"encodeURI",
"encodeURIComponent",
"escape",
"eval",
"hasOwnProperty",
"isFinite",
"isNaN",
"isPrototypeOf",
"parseFloat",
"parseInt",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"undefined",
"unescape",
"valueOf",
];
pub const ES_2015: [&str; 57] = [
"Array",
"ArrayBuffer",
"Boolean",
"DataView",
"Date",
"Error",
"EvalError",
"Float32Array",
"Float64Array",
"Function",
"Infinity",
"Int16Array",
"Int32Array",
"Int8Array",
"JSON",
"Map",
"Math",
"NaN",
"Number",
"Object",
"Promise",
"Proxy",
"RangeError",
"ReferenceError",
"Reflect",
"RegExp",
"Set",
"String",
"Symbol",
"SyntaxError",
"TypeError",
"URIError",
"Uint16Array",
"Uint32Array",
"Uint8Array",
"Uint8ClampedArray",
"WeakMap",
"WeakSet",
"constructor",
"decodeURI",
"decodeURIComponent",
"encodeURI",
"encodeURIComponent",
"escape",
"eval",
"hasOwnProperty",
"isFinite",
"isNaN",
"isPrototypeOf",
"parseFloat",
"parseInt",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"undefined",
"unescape",
"valueOf",
];
pub const ES_2017: [&str; 59] = [
"Array",
"ArrayBuffer",
"Atomics",
"Boolean",
"DataView",
"Date",
"Error",
"EvalError",
"Float32Array",
"Float64Array",
"Function",
"Infinity",
"Int16Array",
"Int32Array",
"Int8Array",
"JSON",
"Map",
"Math",
"NaN",
"Number",
"Object",
"Promise",
"Proxy",
"RangeError",
"ReferenceError",
"Reflect",
"RegExp",
"Set",
"SharedArrayBuffer",
"String",
"Symbol",
"SyntaxError",
"TypeError",
"URIError",
"Uint16Array",
"Uint32Array",
"Uint8Array",
"Uint8ClampedArray",
"WeakMap",
"WeakSet",
"constructor",
"decodeURI",
"decodeURIComponent",
"encodeURI",
"encodeURIComponent",
"escape",
"eval",
"hasOwnProperty",
"isFinite",
"isNaN",
"isPrototypeOf",
"parseFloat",
"parseInt",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"undefined",
"unescape",
"valueOf",
];
pub const ES_2020: [&str; 63] = [
"Array",
"ArrayBuffer",
"Atomics",
"BigInt",
"BigInt64Array",
"BigUint64Array",
"Boolean",
"DataView",
"Date",
"Error",
"EvalError",
"Float32Array",
"Float64Array",
"Function",
"Infinity",
"Int16Array",
"Int32Array",
"Int8Array",
"JSON",
"Map",
"Math",
"NaN",
"Number",
"Object",
"Promise",
"Proxy",
"RangeError",
"ReferenceError",
"Reflect",
"RegExp",
"Set",
"SharedArrayBuffer",
"String",
"Symbol",
"SyntaxError",
"TypeError",
"URIError",
"Uint16Array",
"Uint32Array",
"Uint8Array",
"Uint8ClampedArray",
"WeakMap",
"WeakSet",
"constructor",
"decodeURI",
"decodeURIComponent",
"encodeURI",
"encodeURIComponent",
"escape",
"eval",
"globalThis",
"hasOwnProperty",
"isFinite",
"isNaN",
"isPrototypeOf",
"parseFloat",
"parseInt",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"undefined",
"unescape",
"valueOf",
];
pub const ES_2021: [&str; 66] = [
"AggregateError",
"Array",
"ArrayBuffer",
"Atomics",
"BigInt",
"BigInt64Array",
"BigUint64Array",
"Boolean",
"DataView",
"Date",
"Error",
"EvalError",
"FinalizationRegistry",
"Float32Array",
"Float64Array",
"Function",
"Infinity",
"Int16Array",
"Int32Array",
"Int8Array",
"JSON",
"Map",
"Math",
"NaN",
"Number",
"Object",
"Promise",
"Proxy",
"RangeError",
"ReferenceError",
"Reflect",
"RegExp",
"Set",
"SharedArrayBuffer",
"String",
"Symbol",
"SyntaxError",
"TypeError",
"URIError",
"Uint16Array",
"Uint32Array",
"Uint8Array",
"Uint8ClampedArray",
"WeakMap",
"WeakRef",
"WeakSet",
"constructor",
"decodeURI",
"decodeURIComponent",
"encodeURI",
"encodeURIComponent",
"escape",
"eval",
"globalThis",
"hasOwnProperty",
"isFinite",
"isNaN",
"isPrototypeOf",
"parseFloat",
"parseInt",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"undefined",
"unescape",
"valueOf",
];
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/globals/mod.rs | crates/rome_js_analyze/src/globals/mod.rs | //! This module tracks all globals variables
//!
//! The data in this module is a port of: `<https://github.com/sindresorhus/globals/blob/main/globals.json>`
pub mod browser;
pub mod node;
pub mod runtime;
pub mod typescript;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/utils/case.rs | crates/rome_js_analyze/src/utils/case.rs | /// Represents the [Case] of a string.
///
/// Note that some cases are superset of others.
/// For example, `Case::Camel` includes `Case::Lower`.
/// See [Case::is_compatible_with] for more details.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Case {
/// Unknown case
#[default]
Unknown,
/// camelCase
Camel,
// CONSTANT_CASE
Constant,
/// kebab-case
Kebab,
/// lowercase
Lower,
/// A, B1, C42
NumberableCapital,
/// PascalCase
Pascal,
/// snake_case
Snake,
/// UPPERCASE
Upper,
}
impl Case {
/// Returns the [Case] of `value`.
///
/// If `strict` is `true`, then two consecutive uppercase characters are not
/// allowed in camelCase and PascalCase.
/// For instance, `HTTPServer` is not considered in _PascalCase_ when `strict` is `true`.
///
/// A figure is considered both uppercase and lowercase.
/// Thus, `V8_ENGINE` is in _CONSTANt_CASE_ and `V8Engine` is in _PascalCase_.
///
/// ### Examples
///
/// ```
/// use rome_js_analyze::utils::case::Case;
///
/// assert_eq!(Case::identify("aHttpServer", /* no effect */ true), Case::Camel);
/// assert_eq!(Case::identify("aHTTPServer", true), Case::Unknown);
/// assert_eq!(Case::identify("aHTTPServer", false), Case::Camel);
/// assert_eq!(Case::identify("v8Engine", true), Case::Camel);
///
/// assert_eq!(Case::identify("HTTP_SERVER", /* no effect */ true), Case::Constant);
/// assert_eq!(Case::identify("V8_ENGINE", /* no effect */ true), Case::Constant);
///
/// assert_eq!(Case::identify("http-server", /* no effect */ true), Case::Kebab);
///
/// assert_eq!(Case::identify("httpserver", /* no effect */ true), Case::Lower);
///
/// assert_eq!(Case::identify("T", /* no effect */ true), Case::NumberableCapital);
/// assert_eq!(Case::identify("T1", /* no effect */ true), Case::NumberableCapital);
///
/// assert_eq!(Case::identify("HttpServer", /* no effect */ true), Case::Pascal);
/// assert_eq!(Case::identify("HTTPServer", true), Case::Unknown);
/// assert_eq!(Case::identify("HTTPServer", false), Case::Pascal);
/// assert_eq!(Case::identify("V8Engine", true), Case::Pascal);
///
/// assert_eq!(Case::identify("http_server", /* no effect */ true), Case::Snake);
///
/// assert_eq!(Case::identify("HTTPSERVER", /* no effect */ true), Case::Upper);
///
/// assert_eq!(Case::identify("", /* no effect */ true), Case::Unknown);
/// assert_eq!(Case::identify("_", /* no effect */ true), Case::Unknown);
/// ```
pub fn identify(value: &str, strict: bool) -> Case {
let mut chars = value.chars();
let Some(first_char) = chars.next() else {
return Case::Unknown;
};
if !first_char.is_alphanumeric() {
return Case::Unknown;
}
let mut result = if first_char.is_uppercase() {
Case::NumberableCapital
} else {
Case::Lower
};
let mut previous_char = first_char;
let mut has_consecutive_uppercase = false;
for current_char in chars {
result = match current_char {
'-' => match result {
Case::Kebab | Case::Lower => Case::Kebab,
_ => return Case::Unknown,
},
'_' => match result {
Case::Constant | Case::NumberableCapital | Case::Upper => Case::Constant,
Case::Lower | Case::Snake => Case::Snake,
Case::Camel | Case::Kebab | Case::Pascal | Case::Unknown => {
return Case::Unknown
}
},
_ if current_char.is_uppercase() => {
has_consecutive_uppercase |= previous_char.is_uppercase();
match result {
Case::Camel | Case::Pascal if strict && has_consecutive_uppercase => {
return Case::Unknown
}
Case::Camel | Case::Constant | Case::Pascal => result,
Case::Lower => Case::Camel,
Case::NumberableCapital | Case::Upper => Case::Upper,
Case::Kebab | Case::Snake | Case::Unknown => return Case::Unknown,
}
}
_ if current_char.is_lowercase() => match result {
Case::Camel | Case::Kebab | Case::Lower | Case::Snake => result,
Case::Pascal | Case::NumberableCapital => Case::Pascal,
Case::Upper if !strict || !has_consecutive_uppercase => Case::Pascal,
Case::Constant | Case::Upper | Case::Unknown => return Case::Unknown,
},
_ if current_char.is_numeric() => result, // Figures don't change the case.
_ => return Case::Unknown,
};
previous_char = current_char;
}
result
}
/// Returns `true` if a name that respects `self` also respects `other`.
///
/// For example, a name in [Case::Lower] is also in [Case::Camel], [Case::Kebab] , and [Case::Snake].
/// Thus [Case::Lower] is compatible with [Case::Camel], [Case::Kebab] , and [Case::Snake].
///
/// Any [Case] is compatible with `Case::Unknown` and with itself.
///
/// ### Examples
///
/// ```
/// use rome_js_analyze::utils::case::Case;
///
/// assert!(Case::Lower.is_compatible_with(Case::Camel));
/// assert!(Case::Lower.is_compatible_with(Case::Kebab));
/// assert!(Case::Lower.is_compatible_with(Case::Lower));
/// assert!(Case::Lower.is_compatible_with(Case::Snake));
///
/// assert!(Case::NumberableCapital.is_compatible_with(Case::Constant));
/// assert!(Case::NumberableCapital.is_compatible_with(Case::Pascal));
/// assert!(Case::NumberableCapital.is_compatible_with(Case::Upper));
///
/// assert!(Case::Upper.is_compatible_with(Case::Constant));
///
/// assert!(Case::Camel.is_compatible_with(Case::Unknown));
/// assert!(Case::Constant.is_compatible_with(Case::Unknown));
/// assert!(Case::Kebab.is_compatible_with(Case::Unknown));
/// assert!(Case::Lower.is_compatible_with(Case::Unknown));
/// assert!(Case::NumberableCapital.is_compatible_with(Case::Unknown));
/// assert!(Case::Pascal.is_compatible_with(Case::Unknown));
/// assert!(Case::Snake.is_compatible_with(Case::Unknown));
/// assert!(Case::Upper.is_compatible_with(Case::Unknown));
///
/// assert!(Case::Camel.is_compatible_with(Case::Camel));
/// assert!(Case::Constant.is_compatible_with(Case::Constant));
/// assert!(Case::Kebab.is_compatible_with(Case::Kebab));
/// assert!(Case::Lower.is_compatible_with(Case::Lower));
/// assert!(Case::NumberableCapital.is_compatible_with(Case::NumberableCapital));
/// assert!(Case::Pascal.is_compatible_with(Case::Pascal));
/// assert!(Case::Upper.is_compatible_with(Case::Upper));
/// assert!(Case::Unknown.is_compatible_with(Case::Unknown));
/// ```
pub fn is_compatible_with(self, other: Case) -> bool {
self == other
|| matches!(other, Case::Unknown)
|| matches!((self, other), |(
Case::Lower,
Case::Camel | Case::Kebab | Case::Snake,
)| (
Case::NumberableCapital,
Case::Constant | Case::Pascal | Case::Upper
) | (
Case::Upper,
Case::Constant
))
}
/// Convert `value` to the `self` [Case].
///
/// ### Examples
///
/// ```
/// use rome_js_analyze::utils::case::Case;
///
/// assert_eq!(Case::Camel.convert("Http_SERVER"), "httpServer");
/// assert_eq!(Case::Camel.convert("v8-Engine"), "v8Engine");
///
/// assert_eq!(Case::Constant.convert("HttpServer"), "HTTP_SERVER");
/// assert_eq!(Case::Constant.convert("v8-Engine"), "V8_ENGINE");
///
/// assert_eq!(Case::Kebab.convert("Http_SERVER"), "http-server");
/// assert_eq!(Case::Kebab.convert("v8Engine"), "v8-engine");
///
/// assert_eq!(Case::Lower.convert("Http_SERVER"), "httpserver");
///
/// assert_eq!(Case::NumberableCapital.convert("LONG"), "L");
///
/// assert_eq!(Case::Pascal.convert("http_SERVER"), "HttpServer");
///
/// assert_eq!(Case::Snake.convert("HttpServer"), "http_server");
///
/// assert_eq!(Case::Upper.convert("Http_SERVER"), "HTTPSERVER");
///
/// assert_eq!(Case::Unknown.convert("_"), "_");
/// ```
pub fn convert(self, value: &str) -> String {
if value.is_empty() || matches!(self, Case::Unknown) {
return value.to_string();
}
let mut word_separator = matches!(self, Case::Pascal);
let last_i = value.len() - 1;
let mut output = String::with_capacity(value.len());
let mut first_alphanumeric_i = 0;
for ((i, current), next) in value
.char_indices()
.zip(value.chars().skip(1).map(Some).chain(Some(None)))
{
if (i == 0 || (i == last_i)) && (current == '_' || current == '$') {
output.push(current);
first_alphanumeric_i = 1;
continue;
}
if !current.is_alphanumeric() {
word_separator = true;
continue;
}
if let Some(next) = next {
if i != first_alphanumeric_i && current.is_uppercase() && next.is_lowercase() {
word_separator = true;
}
}
if word_separator {
match self {
Case::Camel
| Case::Lower
| Case::NumberableCapital
| Case::Pascal
| Case::Unknown
| Case::Upper => (),
Case::Constant | Case::Snake => {
output.push('_');
}
Case::Kebab => {
output.push('-');
}
}
}
match self {
Case::Camel | Case::Pascal => {
if word_separator {
output.extend(current.to_uppercase())
} else {
output.extend(current.to_lowercase())
}
}
Case::Constant | Case::Upper => output.extend(current.to_uppercase()),
Case::NumberableCapital => {
if i == first_alphanumeric_i {
output.extend(current.to_uppercase());
}
}
Case::Kebab | Case::Snake | Case::Lower => output.extend(current.to_lowercase()),
Case::Unknown => (),
}
word_separator = false;
if let Some(next) = next {
if current.is_lowercase() && next.is_uppercase() {
word_separator = true;
}
}
}
output
}
}
impl std::fmt::Display for Case {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let repr = match self {
Case::Unknown => "unknown case",
Case::Camel => "camelCase",
Case::Constant => "CONSTANT_CASE",
Case::Kebab => "kebab-case",
Case::Lower => "lowercase",
Case::NumberableCapital => "numberable capital case",
Case::Pascal => "PascalCase",
Case::Snake => "snake_case",
Case::Upper => "UPPERCASE",
};
write!(f, "{}", repr)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_case_convert() {
assert_eq!(Case::Camel.convert("camelCase"), "camelCase");
assert_eq!(Case::Camel.convert("CONSTANT_CASE"), "constantCase");
assert_eq!(Case::Camel.convert("kebab-case"), "kebabCase");
assert_eq!(Case::Camel.convert("PascalCase"), "pascalCase");
assert_eq!(Case::Camel.convert("snake_case"), "snakeCase");
assert_eq!(Case::Camel.convert("Unknown_Style"), "unknownStyle");
assert_eq!(Case::Constant.convert("camelCase"), "CAMEL_CASE");
assert_eq!(Case::Constant.convert("CONSTANT_CASE"), "CONSTANT_CASE");
assert_eq!(Case::Constant.convert("kebab-case"), "KEBAB_CASE");
assert_eq!(Case::Constant.convert("PascalCase"), "PASCAL_CASE");
assert_eq!(Case::Constant.convert("snake_case"), "SNAKE_CASE");
assert_eq!(Case::Constant.convert("Unknown_Style"), "UNKNOWN_STYLE");
assert_eq!(Case::Kebab.convert("camelCase"), "camel-case");
assert_eq!(Case::Kebab.convert("CONSTANT_CASE"), "constant-case");
assert_eq!(Case::Kebab.convert("kebab-case"), "kebab-case");
assert_eq!(Case::Kebab.convert("PascalCase"), "pascal-case");
assert_eq!(Case::Kebab.convert("snake_case"), "snake-case");
assert_eq!(Case::Kebab.convert("Unknown_Style"), "unknown-style");
assert_eq!(Case::Lower.convert("camelCase"), "camelcase");
assert_eq!(Case::Lower.convert("CONSTANT_CASE"), "constantcase");
assert_eq!(Case::Lower.convert("kebab-case"), "kebabcase");
assert_eq!(Case::Lower.convert("PascalCase"), "pascalcase");
assert_eq!(Case::Lower.convert("snake_case"), "snakecase");
assert_eq!(Case::Lower.convert("Unknown_Style"), "unknownstyle");
assert_eq!(Case::NumberableCapital.convert("LONG"), "L");
assert_eq!(Case::Pascal.convert("camelCase"), "CamelCase");
assert_eq!(Case::Pascal.convert("CONSTANT_CASE"), "ConstantCase");
assert_eq!(Case::Pascal.convert("kebab-case"), "KebabCase");
assert_eq!(Case::Pascal.convert("PascalCase"), "PascalCase");
assert_eq!(Case::Pascal.convert("V8Engine"), "V8Engine");
assert_eq!(Case::Pascal.convert("snake_case"), "SnakeCase");
assert_eq!(Case::Pascal.convert("Unknown_Style"), "UnknownStyle");
assert_eq!(Case::Snake.convert("camelCase"), "camel_case");
assert_eq!(Case::Snake.convert("CONSTANT_CASE"), "constant_case");
assert_eq!(Case::Snake.convert("kebab-case"), "kebab_case");
assert_eq!(Case::Snake.convert("PascalCase"), "pascal_case");
assert_eq!(Case::Snake.convert("snake_case"), "snake_case");
assert_eq!(Case::Snake.convert("Unknown_Style"), "unknown_style");
assert_eq!(Case::Upper.convert("camelCase"), "CAMELCASE");
assert_eq!(Case::Upper.convert("CONSTANT_CASE"), "CONSTANTCASE");
assert_eq!(Case::Upper.convert("kebab-case"), "KEBABCASE");
assert_eq!(Case::Upper.convert("PascalCase"), "PASCALCASE");
assert_eq!(Case::Upper.convert("snake_case"), "SNAKECASE");
assert_eq!(Case::Upper.convert("Unknown_Style"), "UNKNOWNSTYLE");
assert_eq!(Case::Unknown.convert("Unknown_Style"), "Unknown_Style");
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/utils/tests.rs | crates/rome_js_analyze/src/utils/tests.rs | use super::rename::*;
use crate::utils::batch::JsBatchMutation;
use rome_js_parser::JsParserOptions;
use rome_js_semantic::{semantic_model, SemanticModelOptions};
use rome_js_syntax::JsSyntaxNode;
use rome_js_syntax::{
AnyJsObjectMember, JsFileSource, JsFormalParameter, JsIdentifierBinding, JsLanguage,
JsVariableDeclarator,
};
use rome_rowan::{AstNode, BatchMutationExt, SyntaxNodeCast};
use std::{any::type_name, fmt::Debug};
/// Search and renames alls bindings where the name contains "a" replacing it to "b".
/// Asserts the renaming worked.
pub fn assert_rename_binding_a_to_b_ok(before: &str, expected: &str) {
let r = rome_js_parser::parse(
before,
JsFileSource::js_module(),
JsParserOptions::default(),
);
let model = semantic_model(&r.tree(), SemanticModelOptions::default());
let bindings: Vec<JsIdentifierBinding> = r
.syntax()
.descendants()
.filter_map(JsIdentifierBinding::cast)
.filter(|x| x.text().contains('a'))
.collect();
let mut batch = r.tree().begin();
for binding in bindings {
let new_name = binding
.name_token()
.unwrap()
.text_trimmed()
.replace('a', "b");
assert!(batch.rename_node_declaration(&model, binding, &new_name));
}
let root = batch.commit();
let after = root.to_string();
assert_eq!(expected, after.as_str());
assert!(!rome_js_parser::test_utils::has_bogus_nodes_or_empty_slots(
&root
));
}
/// Search and renames one binding named "a" to "b".
/// Asserts the renaming fails.
pub fn assert_rename_binding_a_to_b_nok(before: &str) {
let r = rome_js_parser::parse(
before,
JsFileSource::js_module(),
JsParserOptions::default(),
);
let model = semantic_model(&r.tree(), SemanticModelOptions::default());
let binding_a = r
.syntax()
.descendants()
.filter_map(|x| x.cast::<JsIdentifierBinding>())
.find(|x| x.text() == "a")
.unwrap();
let mut batch = r.tree().begin();
assert!(!batch.rename_node_declaration(&model, binding_a, "b"));
}
/// Search an identifier named "a" and remove the entire node of type Anc around it.
/// Asserts the removal worked.
pub fn assert_remove_identifier_a_ok<Anc: AstNode<Language = JsLanguage> + Debug>(
before: &str,
expected: &str,
) {
let r = rome_js_parser::parse(
before,
JsFileSource::js_module(),
JsParserOptions::default(),
);
let identifiers_a: Vec<JsSyntaxNode> = r
.syntax()
.descendants()
.filter(|x| x.tokens().any(|token| token.text_trimmed() == "a"))
.collect();
let node_to_remove = match identifiers_a.as_slice() {
[identifier_a] => identifier_a
.ancestors()
.find_map(|ancestor| ancestor.cast::<Anc>())
.unwrap_or_else(|| {
panic!(
"Trying to remove the {} ancestor of identifier a, but it has no such ancestor",
type_name::<Anc>()
)
}),
_ => panic!(
"Expected exactly one identifier named a, but got {:?}",
identifiers_a
),
};
let mut batch = r.tree().begin();
let batch_result =
if let Some(parameter) = node_to_remove.syntax().clone().cast::<JsFormalParameter>() {
batch.remove_js_formal_parameter(¶meter)
} else if let Some(declarator) = node_to_remove
.syntax()
.clone()
.cast::<JsVariableDeclarator>()
{
batch.remove_js_variable_declarator(&declarator)
} else if let Some(member) = node_to_remove.syntax().clone().cast::<AnyJsObjectMember>() {
batch.remove_js_object_member(&member)
} else {
panic!("Don't know how to remove this node: {:?}", node_to_remove);
};
assert!(batch_result);
let root = batch.commit();
let after = root.to_string();
assert_eq!(expected, after.as_str());
}
#[macro_export]
macro_rules! assert_rename_ok {
($(#[$attr:meta])* $($name:ident, $before:expr, $expected:expr,)*) => {
$(
#[test]
pub fn $name() {
$crate::utils::tests::assert_rename_binding_a_to_b_ok($before, $expected);
}
)*
};
}
#[macro_export]
macro_rules! assert_rename_nok {
($(#[$attr:meta])* $($name:ident, $before:expr,)*) => {
$(
#[test]
pub fn $name() {
$crate::utils::tests::assert_rename_binding_a_to_b_nok($before);
}
)*
};
}
#[macro_export]
macro_rules! assert_remove_ok {
($(#[$attr:meta])* $ancestor:ty, $($name:ident, $before:expr, $expected:expr,)*) => {
$(
#[test]
pub fn $name() {
$crate::utils::tests::assert_remove_identifier_a_ok::<$ancestor>($before, $expected);
}
)*
};
}
#[test]
pub fn ok_find_attributes_by_name() {
let r = rome_js_parser::parse(
r#"<a a="A" c="C" b="B" />"#,
JsFileSource::jsx(),
JsParserOptions::default(),
);
let list = r
.syntax()
.descendants()
.find_map(rome_js_syntax::JsxAttributeList::cast)
.unwrap();
let [a, c, d] = list.find_by_names(["a", "c", "d"]);
assert_eq!(
a.unwrap()
.initializer()
.unwrap()
.value()
.unwrap()
.to_string(),
"\"A\" "
);
assert_eq!(
c.unwrap()
.initializer()
.unwrap()
.value()
.unwrap()
.to_string(),
"\"C\" "
);
assert!(d.is_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/utils/rename.rs | crates/rome_js_analyze/src/utils/rename.rs | use rome_console::fmt::Formatter;
use rome_console::markup;
use rome_diagnostics::{Diagnostic, Location, Severity};
use rome_js_semantic::{ReferencesExtensions, SemanticModel};
use rome_js_syntax::{
binding_ext::AnyJsIdentifierBinding, JsIdentifierAssignment, JsIdentifierBinding, JsLanguage,
JsReferenceIdentifier, JsSyntaxKind, JsSyntaxNode, JsSyntaxToken, TextRange,
TsIdentifierBinding,
};
use rome_rowan::{AstNode, BatchMutation, SyntaxNodeCast, TriviaPiece};
use serde::{Deserialize, Serialize};
use std::fmt;
pub trait RenamableNode {
fn binding(&self, model: &SemanticModel) -> Option<JsSyntaxNode>;
}
impl RenamableNode for JsIdentifierBinding {
fn binding(&self, _: &SemanticModel) -> Option<JsSyntaxNode> {
Some(self.syntax().clone())
}
}
impl RenamableNode for TsIdentifierBinding {
fn binding(&self, _: &SemanticModel) -> Option<JsSyntaxNode> {
Some(self.syntax().clone())
}
}
impl RenamableNode for JsReferenceIdentifier {
fn binding(&self, model: &SemanticModel) -> Option<JsSyntaxNode> {
Some(model.binding(self)?.syntax().clone())
}
}
impl RenamableNode for JsIdentifierAssignment {
fn binding(&self, model: &SemanticModel) -> Option<JsSyntaxNode> {
Some(model.binding(self)?.syntax().clone())
}
}
impl RenamableNode for AnyJsIdentifierBinding {
fn binding(&self, _: &SemanticModel) -> Option<JsSyntaxNode> {
Some(self.syntax().clone())
}
}
pub enum AnyJsRenamableDeclaration {
JsIdentifierBinding(JsIdentifierBinding),
JsReferenceIdentifier(JsReferenceIdentifier),
JsIdentifierAssignment(JsIdentifierAssignment),
TsIdentifierBinding(TsIdentifierBinding),
}
impl RenamableNode for AnyJsRenamableDeclaration {
fn binding(&self, model: &SemanticModel) -> Option<JsSyntaxNode> {
match self {
AnyJsRenamableDeclaration::JsIdentifierBinding(node) => {
RenamableNode::binding(node, model)
}
AnyJsRenamableDeclaration::JsReferenceIdentifier(node) => {
RenamableNode::binding(node, model)
}
AnyJsRenamableDeclaration::JsIdentifierAssignment(node) => {
RenamableNode::binding(node, model)
}
AnyJsRenamableDeclaration::TsIdentifierBinding(node) => {
RenamableNode::binding(node, model)
}
}
}
}
#[derive(Deserialize, Serialize, Debug)]
pub enum RenameError {
CannotFindDeclaration(String),
CannotBeRenamed {
original_name: String,
original_range: TextRange,
new_name: String,
},
}
impl std::fmt::Display for RenameError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RenameError::CannotBeRenamed {
original_name,
new_name,
..
} => {
write!(
f,
"encountered an error while renaming the symbol \"{}\" to \"{}\"",
original_name, new_name
)
}
RenameError::CannotFindDeclaration(_) => {
write!(
f,
"encountered an error finding a declaration at the specified position"
)
}
}
}
}
impl Diagnostic for RenameError {
fn severity(&self) -> Severity {
Severity::Error
}
fn message(&self, fmt: &mut Formatter<'_>) -> std::io::Result<()> {
match self {
RenameError::CannotFindDeclaration(node) => {
fmt.write_markup(
markup! { "Can't find the declaration. Found node "{{node}} }
)
}
RenameError::CannotBeRenamed { original_name, new_name, .. } => {
fmt.write_markup(
markup! { "Can't rename from "<Emphasis>{{original_name}}</Emphasis>" to "<Emphasis>{{new_name}}</Emphasis>"" }
)
}
}
}
fn location(&self) -> Location<'_> {
let location = Location::builder();
if let RenameError::CannotBeRenamed { original_range, .. } = self {
location.span(original_range).build()
} else {
location.build()
}
}
}
impl TryFrom<JsSyntaxNode> for AnyJsRenamableDeclaration {
type Error = RenameError;
fn try_from(node: JsSyntaxNode) -> Result<Self, Self::Error> {
let node_name = node.text_trimmed().to_string();
match node.kind() {
JsSyntaxKind::JS_IDENTIFIER_BINDING => node
.cast::<JsIdentifierBinding>()
.map(AnyJsRenamableDeclaration::JsIdentifierBinding)
.ok_or(Self::Error::CannotFindDeclaration(node_name)),
JsSyntaxKind::JS_REFERENCE_IDENTIFIER => node
.cast::<JsReferenceIdentifier>()
.map(AnyJsRenamableDeclaration::JsReferenceIdentifier)
.ok_or(Self::Error::CannotFindDeclaration(node_name)),
JsSyntaxKind::JS_IDENTIFIER_ASSIGNMENT => node
.cast::<JsIdentifierAssignment>()
.map(AnyJsRenamableDeclaration::JsIdentifierAssignment)
.ok_or(Self::Error::CannotFindDeclaration(node_name)),
JsSyntaxKind::TS_IDENTIFIER_BINDING => node
.cast::<TsIdentifierBinding>()
.map(AnyJsRenamableDeclaration::TsIdentifierBinding)
.ok_or(Self::Error::CannotFindDeclaration(node_name)),
_ => Err(Self::Error::CannotFindDeclaration(node_name)),
}
}
}
pub trait RenameSymbolExtensions {
/// Rename the binding and all its references to "new_name".
fn rename_node_declaration(
&mut self,
model: &SemanticModel,
node: impl RenamableNode,
new_name: &str,
) -> bool;
/// Rename a symbol using the new name from the candidates iterator
/// until the first success.
///
/// A usual use case is to append a suffix to a variable name.
///
/// ```ignore
/// let new_name = "new_name";
/// let candidates = (2..).map(|i| format!("{}{}", new_name, i).into());
/// let candidates = once(Cow::from(new_name)).chain(candidates);
/// batch.try_rename_node_declaration_until_success(model, node, candidates);
/// ```
fn rename_node_declaration_with_retry<S, I>(
&mut self,
model: &SemanticModel,
node: impl RenamableNode + Clone,
candidates: I,
) -> bool
where
S: AsRef<str>,
I: Iterator<Item = S>,
{
for candidate in candidates {
if self.rename_node_declaration(model, node.clone(), candidate.as_ref()) {
return true;
}
}
false
}
/// Rename the binding and all its references to "new_name".
fn rename_any_renamable_node(
&mut self,
model: &SemanticModel,
node: AnyJsRenamableDeclaration,
new_name: &str,
) -> bool {
self.rename_node_declaration(model, node, new_name)
}
}
fn token_with_new_text(token: &JsSyntaxToken, new_text: &str) -> JsSyntaxToken {
let new_text = format!(
"{}{}{}",
token.leading_trivia().text(),
new_text,
token.trailing_trivia().text()
);
let leading = token
.leading_trivia()
.pieces()
.map(|item| TriviaPiece::new(item.kind(), item.text_len()))
.collect::<Vec<_>>();
let trailing = token
.trailing_trivia()
.pieces()
.map(|item| TriviaPiece::new(item.kind(), item.text_len()))
.collect::<Vec<_>>();
JsSyntaxToken::new_detached(JsSyntaxKind::IDENT, new_text.as_str(), leading, trailing)
}
impl RenameSymbolExtensions for BatchMutation<JsLanguage> {
/// Rename the binding and all its references to "new_name".
/// If we can´t rename the binding, the [BatchMutation] is never changes and it is left
/// intact.
fn rename_node_declaration(
&mut self,
model: &SemanticModel,
node: impl RenamableNode,
new_name: &str,
) -> bool {
let prev_binding = match node.binding(model).and_then(AnyJsIdentifierBinding::cast) {
Some(prev_binding) => prev_binding,
None => return false,
};
// We can rename a binding if there is no conflicts in the current scope.
// We can shadow parent scopes, so we don´t check them.
let syntax = prev_binding.syntax();
let scope = model
.scope_hoisted_to(syntax)
.unwrap_or_else(|| model.scope(syntax));
if scope.get_binding(new_name).is_some() {
return false;
}
let name_token = match prev_binding.name_token() {
Ok(name_token) => name_token,
Err(_) => {
return false;
}
};
// We can rename references, if there is no conflicts in any scope
// until the root.
let all_references: Vec<_> = prev_binding.all_references(model).collect();
let mut changes = Vec::with_capacity(all_references.len());
for reference in all_references {
let scope = reference.scope();
if scope
.ancestors()
.find_map(|scope| scope.get_binding(new_name))
.is_some()
{
return false;
}
let prev_token = match reference.syntax().kind() {
JsSyntaxKind::JS_REFERENCE_IDENTIFIER => reference
.syntax()
.clone()
.cast::<JsReferenceIdentifier>()
.and_then(|node| node.value_token().ok()),
JsSyntaxKind::JS_IDENTIFIER_ASSIGNMENT => reference
.syntax()
.clone()
.cast::<JsIdentifierAssignment>()
.and_then(|node| node.name_token().ok()),
_ => None,
};
if let Some(prev_token) = prev_token {
let next_token = token_with_new_text(&prev_token, new_name);
changes.push((prev_token, next_token));
}
}
// Now it is safe to push changes to the batch mutation
// Rename binding
let Ok(prev_name_token) = prev_binding.name_token() else {
return false;
};
let next_name_token = token_with_new_text(&name_token, new_name);
self.replace_token(prev_name_token, next_name_token);
// Rename all references
for (prev_token, next_token) in changes {
self.replace_token(prev_token, next_token);
}
true
}
}
#[cfg(test)]
mod tests {
use crate::utils::rename::RenameError;
use crate::{assert_rename_nok, assert_rename_ok};
use rome_diagnostics::{print_diagnostic_to_string, DiagnosticExt, Error};
use rome_js_syntax::TextRange;
assert_rename_ok! {
ok_rename_declaration,
"let a;",
"let b;",
ok_rename_declaration_with_multiple_declarators,
"let a1, a2;",
"let b1, b2;",
ok_rename_declaration_inner_scope,
"let b; if (true) { let a; }",
"let b; if (true) { let b; }",
ok_rename_read_reference,
"let a; a + 1;",
"let b; b + 1;",
ok_rename_read_before_initit,
"function f() { console.log(a); let a; }",
"function f() { console.log(b); let b; }",
ok_rename_write_reference,
"let a; a = 1;",
"let b; b = 1;",
ok_rename_write_before_init,
"function f() { a = 1; let a; }",
"function f() { b = 1; let b; }",
ok_rename_trivia_is_kept,
"let /*1*/a/*2*/; /*3*/a/*4*/ = 1; /*5*/a/*6*/ + 1",
"let /*1*/b/*2*/; /*3*/b/*4*/ = 1; /*5*/b/*6*/ + 1",
ok_rename_function_same_name,
"function a() { function b() {console.log(2)}; console.log(1); b(); } a();",
"function b() { function b() {console.log(2)}; console.log(1); b(); } b();",
}
assert_rename_nok! {
nok_rename_declaration_conflict_before, "let b; let a;",
nok_rename_declaration_conflict_after, "let a; let b;",
nok_rename_read_reference, "let a; if (true) { let b; a + 1 }",
nok_rename_read_reference_conflict_hoisting_same_scope, "let a; if (true) { a + 1; var b; }",
nok_rename_read_reference_conflict_hoisting_outer_scope, "let a; if (true) { a + 1; } var b;",
nok_rename_write_reference, "let a; if (true) { let b; a = 1 }",
nok_rename_read_reference_parent_scope_conflict, "function f() { let b; if(true) { console.log(a); } } var a;",
nok_rename_function_conflict, "function a() {} function b() {}",
}
fn snap_diagnostic(test_name: &str, diagnostic: Error) {
let content = print_diagnostic_to_string(&diagnostic);
insta::with_settings!({
prepend_module_to_snapshot => false,
}, {
insta::assert_snapshot!(test_name, content);
});
}
#[test]
fn cannot_find_declaration() {
snap_diagnostic(
"cannot_find_declaration",
RenameError::CannotFindDeclaration("async".to_string()).with_file_path("example.js"),
)
}
#[test]
fn cannot_be_renamed() {
let source_code = "async function f() {}";
snap_diagnostic(
"cannot_be_renamed",
RenameError::CannotBeRenamed {
original_name: "async".to_string(),
original_range: TextRange::new(0.into(), 5.into()),
new_name: "await".to_string(),
}
.with_file_path("example.js")
.with_file_source_code(source_code),
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/utils/batch.rs | crates/rome_js_analyze/src/utils/batch.rs | use rome_js_factory::make::jsx_child_list;
use rome_js_syntax::{
AnyJsConstructorParameter, AnyJsFormalParameter, AnyJsObjectMember, AnyJsParameter,
AnyJsxChild, JsConstructorParameterList, JsFormalParameter, JsLanguage, JsObjectMemberList,
JsParameterList, JsSyntaxKind, JsSyntaxNode, JsVariableDeclaration, JsVariableDeclarator,
JsVariableDeclaratorList, JsVariableStatement, JsxChildList,
};
use rome_rowan::{AstNode, AstSeparatedList, BatchMutation};
pub trait JsBatchMutation {
/// Removes the declarator, and:
/// 1 - removes the statement if the declaration only has one declarator;
/// 2 - removes commas around the declarator to keep the list valid.
fn remove_js_variable_declarator(&mut self, declarator: &JsVariableDeclarator) -> bool;
/// Removes the parameter, and:
/// 1 - removes commas around the parameter to keep the list valid.
fn remove_js_formal_parameter(&mut self, parameter: &JsFormalParameter) -> bool;
/// Removes the object member, and:
/// 1 - removes commas around the member to keep the list valid.
fn remove_js_object_member(&mut self, parameter: &AnyJsObjectMember) -> bool;
/// It attempts to add a new element after the given element
///
/// The function appends the elements at the end if `after_element` isn't found
fn add_jsx_elements_after_element<I>(
&mut self,
after_element: &AnyJsxChild,
new_element: I,
) -> bool
where
I: IntoIterator<Item = AnyJsxChild>;
/// It attempts to add a new element before the given element.
fn add_jsx_elements_before_element<I>(
&mut self,
after_element: &AnyJsxChild,
new_elements: I,
) -> bool
where
I: IntoIterator<Item = AnyJsxChild>;
}
fn remove_js_formal_parameter_from_js_parameter_list(
batch: &mut BatchMutation<JsLanguage>,
parameter: &JsFormalParameter,
list: JsSyntaxNode,
) -> Option<bool> {
let list = JsParameterList::cast(list)?;
let mut elements = list.elements();
// Find the parameter we want to remove
// remove its trailing comma, if there is one
let mut previous_element = None;
for element in elements.by_ref() {
if let Ok(node) = element.node() {
match node {
AnyJsParameter::AnyJsFormalParameter(AnyJsFormalParameter::JsFormalParameter(
node,
)) if node == parameter => {
batch.remove_node(node.clone());
if let Ok(Some(comma)) = element.trailing_separator() {
batch.remove_token(comma.clone());
}
break;
}
_ => {}
}
}
previous_element = Some(element);
}
// if it is the last parameter of the list
// removes the comma before this element
if elements.next().is_none() {
if let Some(element) = previous_element {
if let Ok(Some(comma)) = element.trailing_separator() {
batch.remove_token(comma.clone());
}
}
}
Some(true)
}
fn remove_js_formal_parameter_from_js_constructor_parameter_list(
batch: &mut BatchMutation<JsLanguage>,
parameter: &JsFormalParameter,
list: JsSyntaxNode,
) -> Option<bool> {
let list = JsConstructorParameterList::cast(list)?;
let mut elements = list.elements();
// Find the parameter we want to remove
// remove its trailing comma, if there is one
let mut previous_element = None;
for element in elements.by_ref() {
if let Ok(node) = element.node() {
match node {
AnyJsConstructorParameter::AnyJsFormalParameter(
AnyJsFormalParameter::JsFormalParameter(node),
) if node == parameter => {
batch.remove_node(node.clone());
if let Ok(Some(comma)) = element.trailing_separator() {
batch.remove_token(comma.clone());
}
break;
}
_ => {}
}
}
previous_element = Some(element);
}
// if it is the last parameter of the list
// removes the comma before this element
if elements.next().is_none() {
if let Some(element) = previous_element {
if let Ok(Some(comma)) = element.trailing_separator() {
batch.remove_token(comma.clone());
}
}
}
Some(true)
}
impl JsBatchMutation for BatchMutation<JsLanguage> {
fn remove_js_variable_declarator(&mut self, declarator: &JsVariableDeclarator) -> bool {
declarator
.parent::<JsVariableDeclaratorList>()
.and_then(|list| {
let declaration = list.parent::<JsVariableDeclaration>()?;
if list.syntax_list().len() == 1 {
let statement = declaration.parent::<JsVariableStatement>()?;
self.remove_node(statement);
} else {
let mut elements = list.elements();
// Find the declarator we want to remove
// remove its trailing comma, if there is one
let mut previous_element = None;
for element in elements.by_ref() {
if let Ok(node) = element.node() {
if node == declarator {
self.remove_node(node.clone());
if let Ok(Some(comma)) = element.trailing_separator() {
self.remove_token(comma.clone());
}
break;
}
}
previous_element = Some(element);
}
// if it is the last declarator of the list
// removes the comma before this element
let remove_previous_element_comma = match elements.next() {
Some(e) if e.node().is_err() => true,
None => true,
_ => false,
};
if remove_previous_element_comma {
if let Some(element) = previous_element {
if let Ok(Some(comma)) = element.trailing_separator() {
self.remove_token(comma.clone());
}
}
}
}
Some(true)
})
.unwrap_or(false)
}
fn remove_js_formal_parameter(&mut self, parameter: &JsFormalParameter) -> bool {
parameter
.syntax()
.parent()
.and_then(|parent| match parent.kind() {
JsSyntaxKind::JS_PARAMETER_LIST => {
remove_js_formal_parameter_from_js_parameter_list(self, parameter, parent)
}
JsSyntaxKind::JS_CONSTRUCTOR_PARAMETER_LIST => {
remove_js_formal_parameter_from_js_constructor_parameter_list(
self, parameter, parent,
)
}
_ => None,
})
.unwrap_or(false)
}
fn remove_js_object_member(&mut self, member: &AnyJsObjectMember) -> bool {
member
.syntax()
.parent()
.and_then(|parent| {
let parent = JsObjectMemberList::cast(parent)?;
for element in parent.elements() {
if element.node() == Ok(member) {
self.remove_node(member.clone());
if let Ok(Some(comma)) = element.trailing_separator() {
self.remove_token(comma.clone());
}
}
}
Some(true)
})
.unwrap_or(false)
}
fn add_jsx_elements_after_element<I>(
&mut self,
after_element: &AnyJsxChild,
new_elements: I,
) -> bool
where
I: IntoIterator<Item = AnyJsxChild>,
{
let old_list = after_element.parent::<JsxChildList>();
if let Some(old_list) = &old_list {
let jsx_child_list = {
let mut new_items = vec![];
let mut old_elements = old_list.into_iter();
for old_element in old_elements.by_ref() {
let is_needle = old_element == *after_element;
new_items.push(old_element.clone());
if is_needle {
break;
}
}
new_items.extend(new_elements);
new_items.extend(old_elements);
jsx_child_list(new_items)
};
self.replace_node_discard_trivia(old_list.clone(), jsx_child_list);
true
} else {
false
}
}
fn add_jsx_elements_before_element<I>(
&mut self,
before_element: &AnyJsxChild,
new_elements: I,
) -> bool
where
I: IntoIterator<Item = AnyJsxChild>,
{
let old_list = before_element
.syntax()
.parent()
.and_then(JsxChildList::cast);
if let Some(old_list) = &old_list {
let jsx_child_list = {
let mut new_items = vec![];
let mut old_elements = old_list.into_iter().peekable();
while let Some(next_element) = old_elements.peek() {
if next_element == before_element {
break;
}
new_items.push(next_element.clone());
old_elements.next();
}
new_items.extend(new_elements);
new_items.extend(old_elements);
jsx_child_list(new_items)
};
self.replace_node_discard_trivia(old_list.clone(), jsx_child_list);
true
} else {
false
}
}
}
#[cfg(test)]
mod tests {
use crate::assert_remove_ok;
use rome_js_syntax::{AnyJsObjectMember, JsFormalParameter, JsVariableDeclarator};
// Remove JsVariableDeclarator
assert_remove_ok! {
JsVariableDeclarator,
ok_remove_variable_declarator_single,
"let a;",
"",
ok_remove_variable_declarator_fist,
"let a, b;",
"let b;",
ok_remove_variable_declarator_second,
"let b, a;",
"let b;",
ok_remove_variable_declarator_second_trailling_comma,
"let b, a,;",
"let b;",
ok_remove_variable_declarator_middle,
"let b, a, c;",
"let b, c;",
}
// Remove JsFormalParameter from functions
assert_remove_ok! {
JsFormalParameter,
ok_remove_formal_parameter_single,
"function f(a) {}",
"function f() {}",
ok_remove_formal_parameter_first,
"function f(a, b) {}",
"function f(b) {}",
ok_remove_formal_parameter_second,
"function f(b, a) {}",
"function f(b) {}",
ok_remove_formal_parameter_second_trailing_comma,
"function f(b, a,) {}",
"function f(b) {}",
ok_remove_formal_parameter_middle,
"function f(b, a, c) {}",
"function f(b, c) {}",
}
// Remove JsFormalParameter from class constructors
assert_remove_ok! {
JsFormalParameter,
ok_remove_formal_parameter_from_class_constructor_single,
"class A { constructor(a) {} }",
"class A { constructor() {} }",
ok_remove_formal_parameter_from_class_constructor_first,
"class A { constructor(a, b) {} }",
"class A { constructor(b) {} }",
ok_remove_formal_parameter_from_class_constructor_second,
"class A { constructor(b, a) {} }",
"class A { constructor(b) {} }",
ok_remove_formal_parameter_from_class_constructor_second_trailing_comma,
"class A { constructor(b, a,) {} }",
"class A { constructor(b) {} }",
ok_remove_formal_parameter_from_class_constructor_middle,
"class A { constructor(b, a, c) {} }",
"class A { constructor(b, c) {} }",
}
// Remove JsAnyObjectMember from object expression
assert_remove_ok! {
AnyJsObjectMember,
ok_remove_first_member,
"({ a: 1, b: 2 })",
"({ b: 2 })",
ok_remove_middle_member,
"({ z: 1, a: 2, b: 3 })",
"({ z: 1, b: 3 })",
ok_remove_last_member,
"({ z: 1, a: 2 })",
"({ z: 1, })",
ok_remove_last_member_trailing_comma,
"({ z: 1, a: 2, })",
"({ z: 1, })",
ok_remove_only_member,
"({ a: 2 })",
"({ })",
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/utils/escape.rs | crates/rome_js_analyze/src/utils/escape.rs | /// Utility function to escape strings.
///
/// This function iterates over characters of strings and adds an escape character if needed.
/// If there are already odd number of escape characters before the character needs to be escaped,
/// the escape character is not added.
///
/// **sample case**
///
/// | needs_escaping | unescaped | escaped |
/// |:----:|:---------:|:----------:|
/// | `${` | `${abc` | `\${abc` |
/// | `${` | `\${abc` | `\${abc` |
/// | `${` | `\\${abc` | `\\\${abc` |
///
/// # Examples
///
/// ```
/// use rome_js_analyze::utils::escape::escape;
///
/// let escaped_str_1 = escape("${abc", &["${"], '\\');
/// assert_eq!(escaped_str_1, r#"\${abc"#);
///
/// let escaped_str_2 = escape(r#"\${abc"#, &["${"], '\\');
/// assert_eq!(escaped_str_2, r#"\${abc"#);
///
/// let escaped_str_3 = escape("${ `", &["${", "`"], '\\');
/// assert_eq!(escaped_str_3, r#"\${ \`"#);
/// ```
pub fn escape<'a>(
unescaped_string: &'a str,
needs_escaping: &[&str],
escaping_char: char,
) -> std::borrow::Cow<'a, str> {
let mut escaped = String::new();
let mut iter = unescaped_string.char_indices();
let mut is_escaped = false;
'unescaped: while let Some((idx, chr)) = iter.next() {
if chr == escaping_char {
is_escaped = !is_escaped;
} else {
for candidate in needs_escaping {
if unescaped_string[idx..].starts_with(candidate) {
if !is_escaped {
if escaped.is_empty() {
escaped = String::with_capacity(unescaped_string.len() * 2);
escaped.push_str(&unescaped_string[0..idx]);
}
escaped.push(escaping_char);
escaped.push_str(candidate);
for _ in candidate.chars().skip(1) {
iter.next();
}
continue 'unescaped;
} else {
is_escaped = false;
}
}
}
}
if !escaped.is_empty() {
escaped.push(chr);
}
}
if escaped.is_empty() {
std::borrow::Cow::Borrowed(unescaped_string)
} else {
std::borrow::Cow::Owned(escaped)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ok_escape_dollar_signs_and_backticks() {
assert_eq!(escape("abc", &["${"], '\\'), "abc");
assert_eq!(escape("abc", &["`"], '\\'), "abc");
assert_eq!(escape(r#"abc\"#, &["`"], '\\'), r#"abc\"#);
assert_eq!(escape("abc $ bca", &["${"], '\\'), "abc $ bca");
assert_eq!(escape("abc ${a} bca", &["${"], '\\'), r#"abc \${a} bca"#);
assert_eq!(
escape("abc ${} ${} bca", &["${"], '\\'),
r#"abc \${} \${} bca"#
);
assert_eq!(escape(r#"\`"#, &["`"], '\\'), r#"\`"#);
assert_eq!(escape(r#"\${}"#, &["${"], '\\'), r#"\${}"#);
assert_eq!(escape(r#"\\`"#, &["`"], '\\'), r#"\\\`"#);
assert_eq!(escape(r#"\\${}"#, &["${"], '\\'), r#"\\\${}"#);
assert_eq!(escape(r#"\\\`"#, &["`"], '\\'), r#"\\\`"#);
assert_eq!(escape(r#"\\\${}"#, &["${"], '\\'), r#"\\\${}"#);
assert_eq!(escape("abc", &["${", "`"], '\\'), "abc");
assert_eq!(escape("${} `", &["${", "`"], '\\'), r#"\${} \`"#);
assert_eq!(
escape(r#"abc \${a} \`bca"#, &["${", "`"], '\\'),
r#"abc \${a} \`bca"#
);
assert_eq!(
escape(r#"abc \${bca}"#, &["${", "`"], '\\'),
r#"abc \${bca}"#
);
assert_eq!(escape(r#"abc \`bca"#, &["${", "`"], '\\'), r#"abc \`bca"#);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/syntax/nursery.rs | crates/rome_js_analyze/src/syntax/nursery.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_analyze::declare_group;
pub(crate) mod no_duplicate_private_class_members;
pub(crate) mod no_super_without_extends;
declare_group! {
pub (crate) Nursery {
name : "nursery" ,
rules : [
self :: no_duplicate_private_class_members :: NoDuplicatePrivateClassMembers ,
self :: no_super_without_extends :: NoSuperWithoutExtends ,
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/syntax/nursery/no_super_without_extends.rs | crates/rome_js_analyze/src/syntax/nursery/no_super_without_extends.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::category;
use rome_js_syntax::{JsClassDeclaration, JsSuperExpression};
use rome_rowan::AstNode;
declare_rule! {
/// Catch a `SyntaxError` when writing calling `super()` on a class that doesn't extends any class
///
/// ## Examples
///
/// ```js
/// class A {
// constructor() {
// super()
// }
// }
/// ```
pub(crate) NoSuperWithoutExtends {
version: "10.0.0",
name: "noSuperWithoutExtends",
recommended: false,
}
}
impl Rule for NoSuperWithoutExtends {
type Query = Ast<JsSuperExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if let Some(class_declaration) =
node.syntax().ancestors().find_map(JsClassDeclaration::cast)
{
if class_declaration.extends_clause().is_none() {
return Some(());
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
category!("parse/noSuperWithoutExtends"),
node.syntax().text_trimmed_range(),
markup! {
"super() is only valid in derived class constructors"
},
))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/syntax/nursery/no_duplicate_private_class_members.rs | crates/rome_js_analyze/src/syntax/nursery/no_duplicate_private_class_members.rs | use std::collections::{HashMap, HashSet};
use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_diagnostics::category;
use rome_js_syntax::{AnyJsClassMember, JsClassMemberList, TextRange};
use rome_rowan::AstNode;
declare_rule! {
/// Catch a `SyntaxError` when defining duplicate private class members.
///
/// ## Examples
///
/// ```js
/// class A {
/// #foo;
/// #foo;
// }
/// ```
pub(crate) NoDuplicatePrivateClassMembers {
version: "12.0.0",
name: "noDuplicatePrivateClassMembers",
recommended: false,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum MemberType {
Normal,
Getter,
Setter,
}
impl Rule for NoDuplicatePrivateClassMembers {
type Query = Ast<JsClassMemberList>;
type State = (String, TextRange);
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let mut defined_members: HashMap<String, HashSet<MemberType>> = HashMap::new();
let node = ctx.query();
node.into_iter()
.filter_map(|member| {
let member_name = member
.name()
.ok()??
.as_js_private_class_member_name()?
.text();
let member_type = match member {
AnyJsClassMember::JsGetterClassMember(_) => MemberType::Getter,
AnyJsClassMember::JsMethodClassMember(_) => MemberType::Normal,
AnyJsClassMember::JsPropertyClassMember(_) => MemberType::Normal,
AnyJsClassMember::JsSetterClassMember(_) => MemberType::Setter,
_ => return None,
};
if let Some(stored_members) = defined_members.get_mut(&member_name) {
if stored_members.contains(&MemberType::Normal)
|| stored_members.contains(&member_type)
|| member_type == MemberType::Normal
{
return Some((member_name, member.range()));
} else {
stored_members.insert(member_type);
}
} else {
defined_members.insert(member_name, HashSet::from([member_type]));
}
None
})
.collect()
}
fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let (member_name, range) = state;
let diagnostic = RuleDiagnostic::new(
category!("parse/noDuplicatePrivateClassMembers"),
range,
format!("Duplicate private class member {:?}", member_name),
);
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/control_flow/visitor.rs | crates/rome_js_analyze/src/control_flow/visitor.rs | use std::any::TypeId;
use rome_analyze::{merge_node_visitors, Visitor, VisitorContext};
use rome_js_syntax::{
AnyJsFunction, JsConstructorClassMember, JsGetterClassMember, JsGetterObjectMember, JsLanguage,
JsMethodClassMember, JsMethodObjectMember, JsModule, JsScript, JsSetterClassMember,
JsSetterObjectMember, JsStaticInitializationBlockClassMember,
};
use rome_rowan::{declare_node_union, AstNode, SyntaxError, SyntaxResult};
use crate::ControlFlowGraph;
use super::{nodes::*, FunctionBuilder};
/// Return a new instance of the [ControlFlowVisitor]
pub(crate) fn make_visitor() -> impl Visitor<Language = JsLanguage> {
ControlFlowVisitor::new()
}
/// Wrapper macro for [merge_node_visitors], implements additional control
/// flow-related utilities on top of the generated visitor
macro_rules! declare_visitor {
( $vis:vis $name:ident { $( $id:ident: $visitor:ty, )* } ) => {
merge_node_visitors! {
$vis $name {
function: FunctionVisitor,
$( $id: VisitorAdapter<$visitor>, )*
}
}
/// Slice of the merged visitor state stack cut off at the current function
pub(super) struct StatementStack<'a> {
pub(super) stack: &'a mut [(TypeId, usize)],
$(
#[cfg(debug_assertions)]
$id: (usize, &'a mut [(usize, VisitorAdapter<$visitor>)]),
#[cfg(not(debug_assertions))]
$id: &'a mut [(usize, VisitorAdapter<$visitor>)],
)*
}
impl<'a> StatementStack<'a> {
/// Split the visitor state at the topmost function, returning the
/// corresponding function visitor and the rest of the stack above it
fn new(visitor: &'a mut $name) -> Option<(&mut FunctionVisitor, Self)> {
let (index, builder) = visitor.function.last_mut()?;
Some((builder, Self {
stack: {
let stack_len = visitor.stack.len();
visitor.stack.get_mut(*index + 1..).unwrap_or_else(|| panic!("stack index out of bounds: {} >= {stack_len}", *index + 1))
},
$(
// For safety, cut off the stack slices below the start
// of the current function in debug mode
#[cfg(debug_assertions)]
$id: (
visitor
.$id
.iter()
.rposition(|(stack_index, _)| *stack_index < *index)
.map_or(0, |index| (index + 1).min(visitor.$id.len().saturating_sub(1))),
&mut visitor.$id,
),
#[cfg(not(debug_assertions))]
$id: &mut visitor.$id,
)*
}))
}
}
$( impl<'a> MergedVisitor<'a, $visitor> for StatementStack<'a> {
fn read_top(self) -> SyntaxResult<&'a mut $visitor> {
#[cfg(debug_assertions)]
let (_, visitor) =
self.$id.1.last_mut().ok_or(::rome_rowan::SyntaxError::MissingRequiredChild)?;
#[cfg(not(debug_assertions))]
let (_, visitor) =
self.$id.last_mut().ok_or(::rome_rowan::SyntaxError::MissingRequiredChild)?;
let VisitorAdapter(visitor) = visitor;
let visitor = visitor.as_mut().map_err(|err| *err)?;
Ok(visitor)
}
fn try_downcast(&'a self, type_id: TypeId, index: usize) -> Option<&'a $visitor> {
if type_id != TypeId::of::<VisitorAdapter<$visitor>>() {
return None;
}
#[cfg(debug_assertions)]
let (_, visitor) = index.checked_sub(self.$id.0)
.and_then(|index| self.$id.1.get(index))
.unwrap_or_else(|| panic!(concat!(stringify!($id), " index out of bounds: {} + {} >= {}"), index, self.$id.0, self.$id.1.len()));
#[cfg(not(debug_assertions))]
let (_, visitor) = self.$id.get(index)
.unwrap_or_else(|| panic!(concat!(stringify!($id), " index out of bounds: {} >= {}"), index, self.$id.len()));
let VisitorAdapter(visitor) = visitor;
let visitor = visitor.as_ref().ok()?;
Some(visitor)
}
} )*
};
}
declare_visitor! {
ControlFlowVisitor {
statement: StatementVisitor,
block: BlockVisitor,
try_stmt: TryVisitor,
catch: CatchVisitor,
finally: FinallyVisitor,
if_stmt: IfVisitor,
else_stmt: ElseVisitor,
switch: SwitchVisitor,
case: CaseVisitor,
for_stmt: ForVisitor,
for_in: ForInVisitor,
for_of: ForOfVisitor,
while_stmt: WhileVisitor,
do_while: DoWhileVisitor,
break_stmt: BreakVisitor,
continue_stmt: ContinueVisitor,
return_stmt: ReturnVisitor,
throw: ThrowVisitor,
variable: VariableVisitor,
}
}
/// Utility implemented for [StatementStack] in the [declare_visitor] macro,
/// allows type checked access into the visitor state stack
pub(super) trait MergedVisitor<'a, N> {
fn read_top(self) -> SyntaxResult<&'a mut N>;
fn try_downcast(&'a self, type_id: TypeId, index: usize) -> Option<&'a N>;
}
// Wrapper methods on top of the `MergedVisitor` trait to support for the
// "turbofish" (`::<>`) syntax
impl<'a> StatementStack<'a> {
pub(super) fn read_top<N>(self) -> SyntaxResult<&'a mut N>
where
Self: MergedVisitor<'a, N>,
{
MergedVisitor::read_top(self)
}
pub(super) fn try_downcast<N>(&'a self, type_id: TypeId, index: usize) -> Option<&'a N>
where
Self: MergedVisitor<'a, N>,
{
MergedVisitor::try_downcast(self, type_id, index)
}
}
pub(super) struct FunctionVisitor {
builder: Option<FunctionBuilder>,
}
declare_node_union! {
pub(crate) AnyJsControlFlowRoot = JsModule
| JsScript
| AnyJsFunction
| JsGetterObjectMember
| JsSetterObjectMember
| JsMethodObjectMember
| JsConstructorClassMember
| JsMethodClassMember
| JsGetterClassMember
| JsSetterClassMember
| JsStaticInitializationBlockClassMember
}
impl rome_analyze::NodeVisitor<ControlFlowVisitor> for FunctionVisitor {
type Node = AnyJsControlFlowRoot;
fn enter(
node: Self::Node,
_: &mut VisitorContext<JsLanguage>,
_: &mut ControlFlowVisitor,
) -> Self {
Self {
builder: Some(FunctionBuilder::new(node.into_syntax())),
}
}
fn exit(self, _: Self::Node, ctx: &mut VisitorContext<JsLanguage>, _: &mut ControlFlowVisitor) {
if let Some(builder) = self.builder {
ctx.match_query(ControlFlowGraph {
graph: builder.finish(),
});
}
}
}
/// Wrapper trait for [rome_analyze::NodeVisitor] adding control flow specific
/// utilities (error handling and automatic [FunctionBuilder] injection)
pub(super) trait NodeVisitor: Sized {
type Node: AstNode<Language = JsLanguage>;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self>;
fn exit(self, _: Self::Node, _: &mut FunctionBuilder, _: StatementStack) -> SyntaxResult<()> {
Ok(())
}
}
/// Wrapper type implementing [rome_analyze::NodeVisitor] for types
/// implementing the control-flow specific [NodeVisitor] trait
pub(super) struct VisitorAdapter<V>(SyntaxResult<V>);
impl<V> rome_analyze::NodeVisitor<ControlFlowVisitor> for VisitorAdapter<V>
where
V: NodeVisitor,
{
type Node = V::Node;
fn enter(
node: Self::Node,
_: &mut VisitorContext<JsLanguage>,
stack: &mut ControlFlowVisitor,
) -> Self {
let (visitor, stack) = match StatementStack::new(stack) {
Some((builder, stack)) => (builder, stack),
None => return Self(Err(SyntaxError::MissingRequiredChild)),
};
let result = if let Some(builder) = visitor.builder.as_mut() {
let result = V::enter(node, builder, stack);
if result.is_err() {
visitor.builder.take();
}
result
} else {
Err(SyntaxError::MissingRequiredChild)
};
Self(result)
}
fn exit(
self,
node: Self::Node,
_: &mut VisitorContext<JsLanguage>,
stack: &mut ControlFlowVisitor,
) {
let state = match self {
Self(Ok(state)) => state,
_ => return,
};
let (visitor, stack) = match StatementStack::new(stack) {
Some((builder, stack)) => (builder, stack),
None => return,
};
if let Some(builder) = visitor.builder.as_mut() {
if state.exit(node, builder, stack).is_err() {
visitor.builder.take();
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/control_flow/nodes.rs | crates/rome_js_analyze/src/control_flow/nodes.rs | mod block;
mod break_stmt;
mod continue_stmt;
mod do_while;
mod for_in;
mod for_of;
mod for_stmt;
mod if_stmt;
mod return_stmt;
mod statement;
mod switch_stmt;
mod throw_stmt;
mod try_catch;
mod variable;
mod while_stmt;
pub(super) use block::*;
pub(super) use break_stmt::*;
pub(super) use continue_stmt::*;
pub(super) use do_while::*;
pub(super) use for_in::*;
pub(super) use for_of::*;
pub(super) use for_stmt::*;
pub(super) use if_stmt::*;
pub(super) use return_stmt::*;
pub(super) use statement::*;
pub(super) use switch_stmt::*;
pub(super) use throw_stmt::*;
pub(super) use try_catch::*;
pub(super) use variable::*;
pub(super) use while_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/control_flow/nodes/switch_stmt.rs | crates/rome_js_analyze/src/control_flow/nodes/switch_stmt.rs | use rome_control_flow::builder::BlockId;
use rome_js_syntax::{AnyJsSwitchClause, JsLabeledStatement, JsSwitchStatement, JsSyntaxToken};
use rome_rowan::{AstNode, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
pub(in crate::control_flow) struct SwitchVisitor {
entry_block: BlockId,
// `label` and `break_block` are used by the `BreakVisitor`
pub(super) label: Option<JsSyntaxToken>,
pub(super) break_block: BlockId,
/// Flag used by the [CaseVisitor] to check if it's the first case clause
/// in a switch statement (used to implement fallthrough)
is_first_case_clause: bool,
default_block: Option<(BlockId, JsSyntaxToken)>,
}
impl NodeVisitor for SwitchVisitor {
type Node = JsSwitchStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
// Execute the discriminant expression as a side-effect
builder.append_statement().with_node(node.discriminant()?);
let entry_block = builder.cursor();
let break_block = builder.append_block();
let label = node
.parent::<JsLabeledStatement>()
.and_then(|label| label.label_token().ok());
Ok(Self {
entry_block,
label,
break_block,
is_first_case_clause: true,
default_block: None,
})
}
fn exit(
self,
_: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<()> {
let Self {
entry_block,
break_block,
is_first_case_clause,
..
} = self;
// Append an implicit jump to the break block at the end of the last
// clause, if the statement had at least one
if !is_first_case_clause {
builder.append_jump(false, break_block);
}
// Also implicitly jump to either the default block or the break block
// (over the switch statement) at the end of the entry block if no case
// was matched
builder.set_cursor(entry_block);
if let Some((block, token)) = self.default_block {
builder.append_jump(false, block).with_node(token);
} else {
builder.append_jump(false, break_block);
}
builder.set_cursor(break_block);
Ok(())
}
}
pub(in crate::control_flow) struct CaseVisitor;
impl NodeVisitor for CaseVisitor {
type Node = AnyJsSwitchClause;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
stack: StatementStack,
) -> SyntaxResult<Self> {
let case_block = builder.append_block();
let switch_stmt = stack.read_top::<SwitchVisitor>()?;
if !switch_stmt.is_first_case_clause {
builder.append_jump(false, case_block);
} else {
switch_stmt.is_first_case_clause = false;
}
match node {
AnyJsSwitchClause::JsCaseClause(node) => {
builder.set_cursor(switch_stmt.entry_block);
builder
.append_jump(true, case_block)
.with_node(node.test()?.into_syntax());
}
AnyJsSwitchClause::JsDefaultClause(node) => {
let token = node.default_token()?;
switch_stmt.default_block = Some((case_block, token));
}
}
builder.set_cursor(case_block);
Ok(Self)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/control_flow/nodes/variable.rs | crates/rome_js_analyze/src/control_flow/nodes/variable.rs | use rome_js_syntax::JsVariableStatement;
use rome_rowan::{AstNode, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
pub(in crate::control_flow) struct VariableVisitor;
impl NodeVisitor for VariableVisitor {
type Node = JsVariableStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
let declaration = node.declaration()?;
for declarator in declaration.declarators() {
if let Some(initializer) = declarator?.initializer() {
let expr = initializer.expression()?;
builder.append_statement().with_node(expr.into_syntax());
}
}
Ok(Self)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/control_flow/nodes/break_stmt.rs | crates/rome_js_analyze/src/control_flow/nodes/break_stmt.rs | use std::any::TypeId;
use rome_js_syntax::JsBreakStatement;
use rome_rowan::{AstNode, SyntaxError, SyntaxResult};
use crate::control_flow::{
nodes::{
BlockVisitor, DoWhileVisitor, ForInVisitor, ForOfVisitor, ForVisitor, SwitchVisitor,
WhileVisitor,
},
visitor::{FunctionVisitor, NodeVisitor, StatementStack, VisitorAdapter},
FunctionBuilder,
};
pub(in crate::control_flow) struct BreakVisitor;
impl NodeVisitor for BreakVisitor {
type Node = JsBreakStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
state: StatementStack,
) -> SyntaxResult<Self> {
let label = node.label_token();
let break_block = state
.stack
.iter()
.rev()
.take_while(|(type_id, _)| *type_id != TypeId::of::<VisitorAdapter<FunctionVisitor>>())
.find_map(|(type_id, index)| {
let (block_label, block) = if let Some(visitor) =
state.try_downcast::<ForVisitor>(*type_id, *index)
{
(visitor.label.as_ref(), visitor.break_block)
} else if let Some(visitor) = state.try_downcast::<ForInVisitor>(*type_id, *index) {
(visitor.label.as_ref(), visitor.break_block)
} else if let Some(visitor) = state.try_downcast::<ForOfVisitor>(*type_id, *index) {
(visitor.label.as_ref(), visitor.break_block)
} else if let Some(visitor) = state.try_downcast::<WhileVisitor>(*type_id, *index) {
(visitor.label.as_ref(), visitor.break_block)
} else if let Some(visitor) = state.try_downcast::<DoWhileVisitor>(*type_id, *index)
{
(visitor.label.as_ref(), visitor.break_block)
} else if let Some(visitor) = state.try_downcast::<SwitchVisitor>(*type_id, *index)
{
(visitor.label.as_ref(), visitor.break_block)
} else if let Some(visitor) = state.try_downcast::<BlockVisitor>(*type_id, *index) {
let (label, block) = visitor.break_block.as_ref()?;
(Some(label), *block)
} else {
return None;
};
match (block_label, &label) {
(Some(a), Some(b)) => {
if a.text_trimmed() == b.text_trimmed() {
Some(block)
} else {
None
}
}
(None, None) => Some(block),
_ => None,
}
})
.ok_or(SyntaxError::MissingRequiredChild)?;
builder
.append_jump(false, break_block)
.with_node(node.into_syntax());
Ok(Self)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/control_flow/nodes/throw_stmt.rs | crates/rome_js_analyze/src/control_flow/nodes/throw_stmt.rs | use rome_js_syntax::JsThrowStatement;
use rome_rowan::{AstNode, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
pub(in crate::control_flow) struct ThrowVisitor;
impl NodeVisitor for ThrowVisitor {
type Node = JsThrowStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
builder.append_return().with_node(node.into_syntax());
Ok(Self)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/control_flow/nodes/for_stmt.rs | crates/rome_js_analyze/src/control_flow/nodes/for_stmt.rs | use rome_control_flow::builder::BlockId;
use rome_js_syntax::{JsForStatement, JsLabeledStatement, JsSyntaxToken};
use rome_rowan::{AstNode, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
pub(in crate::control_flow) struct ForVisitor {
// `label`, `continue_block` and `break_block` are used by the
// `ContinueVisitor` and `BreakVisitor`
pub(super) label: Option<JsSyntaxToken>,
pub(super) continue_block: BlockId,
pub(super) break_block: BlockId,
cond_block: BlockId,
loop_block: BlockId,
}
impl NodeVisitor for ForVisitor {
type Node = JsForStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
// Immediately evaluate the initializer statement
if let Some(initializer) = node.initializer() {
builder
.append_statement()
.with_node(initializer.into_syntax());
}
// Create the condition block and unconditionally jump to it
let cond_block = builder.append_block();
builder.append_jump(false, cond_block);
// Create the continue block and break block immediately
let continue_block = builder.append_block();
let break_block = builder.append_block();
// Fill the continue block
builder.set_cursor(continue_block);
if let Some(update) = node.update() {
builder.append_statement().with_node(update.into_syntax());
}
builder.append_jump(false, cond_block);
// Create the loop block and fill it with the loop body statement
let loop_block = builder.append_block();
builder.set_cursor(loop_block);
let label = node
.parent::<JsLabeledStatement>()
.and_then(|label| label.label_token().ok());
Ok(Self {
label,
continue_block,
break_block,
cond_block,
loop_block,
})
}
fn exit(
self,
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<()> {
let Self {
continue_block,
break_block,
cond_block,
loop_block,
..
} = self;
// Insert an unconditional jump to the continue block at the end of the loop body
builder.append_jump(false, continue_block);
// Write the condition block
builder.set_cursor(cond_block);
if let Some(test) = node.test() {
builder
.append_jump(true, loop_block)
.with_node(test.syntax().clone());
} else {
builder.append_jump(false, loop_block);
}
builder.append_jump(false, break_block);
// Set the cursor to the break block and move of to the next statement
builder.set_cursor(break_block);
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/control_flow/nodes/if_stmt.rs | crates/rome_js_analyze/src/control_flow/nodes/if_stmt.rs | use rome_control_flow::builder::BlockId;
use rome_js_syntax::{JsElseClause, JsIfStatement};
use rome_rowan::{AstNode, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
pub(in crate::control_flow) struct IfVisitor {
/// Saved position of the control flow cursor before entering the statement
entry_block: BlockId,
/// First block of the consequent for this statement
consequent_start: BlockId,
/// Last block of the consequent for this statement, implicitly jumps to
/// the next block
/// This is only set if the statement has an else clause (by the [ElseVisitor]),
/// otherwise this information is derived from the cursor of the function builder
consequent_end: Option<BlockId>,
/// Start and end block of the alternate of this statement, set by the
/// [ElseVisitor] if this node has an else clause
alt_block: Option<(BlockId, BlockId)>,
}
impl NodeVisitor for IfVisitor {
type Node = JsIfStatement;
fn enter(
_: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
let entry_block = builder.cursor();
let consequent_start = builder.append_block();
builder.set_cursor(consequent_start);
Ok(Self {
entry_block,
consequent_start,
consequent_end: None,
alt_block: None,
})
}
fn exit(
self,
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<()> {
let consequent_end = self.consequent_end.unwrap_or_else(|| builder.cursor());
let alt_block = self.alt_block;
let next_block = builder.append_block();
builder.set_cursor(self.entry_block);
// If this node has an else clause the start and end of `alt_block`
// were generated by the `ElseVisitor`
if let Some((alt_start, alt_end)) = alt_block {
builder
.append_jump(true, self.consequent_start)
.with_node(node.test()?.into_syntax());
builder.append_jump(false, alt_start);
builder.set_cursor(alt_end);
builder.append_jump(false, next_block);
} else {
builder
.append_jump(true, self.consequent_start)
.with_node(node.test()?.into_syntax());
builder.append_jump(false, next_block);
}
builder.set_cursor(consequent_end);
builder.append_jump(false, next_block);
builder.set_cursor(next_block);
Ok(())
}
}
pub(in crate::control_flow) struct ElseVisitor {
consequent_block: BlockId,
alt_block: BlockId,
}
impl NodeVisitor for ElseVisitor {
type Node = JsElseClause;
fn enter(
_: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
let consequent_block = builder.cursor();
let alt_block = builder.append_block();
builder.set_cursor(alt_block);
Ok(Self {
consequent_block,
alt_block,
})
}
fn exit(
self,
_: Self::Node,
builder: &mut FunctionBuilder,
stack: StatementStack,
) -> SyntaxResult<()> {
let if_state = stack.read_top::<IfVisitor>()?;
if_state.consequent_end = Some(self.consequent_block);
if_state.alt_block = Some((self.alt_block, builder.cursor()));
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/control_flow/nodes/block.rs | crates/rome_js_analyze/src/control_flow/nodes/block.rs | use rome_control_flow::builder::BlockId;
use rome_js_syntax::{JsBlockStatement, JsLabeledStatement, JsSyntaxToken};
use rome_rowan::{AstNode, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
pub(in crate::control_flow) struct BlockVisitor {
/// If this block has a label, this contains the label token and the ID of
/// the break block to use as a jump target in `BreakVisitor`
pub(super) break_block: Option<(JsSyntaxToken, BlockId)>,
}
impl NodeVisitor for BlockVisitor {
type Node = JsBlockStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
let break_block = match node.parent::<JsLabeledStatement>() {
Some(label) => {
let label = label.label_token()?;
let block = builder.append_block();
Some((label, block))
}
None => None,
};
Ok(Self { break_block })
}
fn exit(
self,
_: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<()> {
if let Some((_, block)) = self.break_block {
builder.append_jump(false, block);
builder.set_cursor(block);
}
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/control_flow/nodes/do_while.rs | crates/rome_js_analyze/src/control_flow/nodes/do_while.rs | use rome_control_flow::builder::BlockId;
use rome_js_syntax::{JsDoWhileStatement, JsLabeledStatement, JsSyntaxToken};
use rome_rowan::{AstNode, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
pub(in crate::control_flow) struct DoWhileVisitor {
// `label`, `continue_block` and `break_block` are used by the
// `ContinueVisitor` and `BreakVisitor`
pub(super) label: Option<JsSyntaxToken>,
pub(super) continue_block: BlockId,
pub(super) break_block: BlockId,
body_block: BlockId,
}
impl NodeVisitor for DoWhileVisitor {
type Node = JsDoWhileStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
let body_block = builder.append_block();
// Unconditionally jump into the loop
builder.append_jump(false, body_block);
let continue_block = builder.append_block();
let break_block = builder.append_block();
let label = node
.parent::<JsLabeledStatement>()
.and_then(|label| label.label_token().ok());
// Fill the body block
builder.set_cursor(body_block);
Ok(Self {
label,
continue_block,
break_block,
body_block,
})
}
fn exit(
self,
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<()> {
let Self {
continue_block,
break_block,
body_block,
..
} = self;
// Insert an implicit jump to the continue block at the end of the loop
builder.append_jump(false, continue_block);
// Fill the continue block
builder.set_cursor(continue_block);
builder
.append_jump(true, body_block)
.with_node(node.test()?.into_syntax());
builder.append_jump(false, break_block);
// Set the cursor to the break block and move to the next statement
builder.set_cursor(break_block);
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/control_flow/nodes/try_catch.rs | crates/rome_js_analyze/src/control_flow/nodes/try_catch.rs | use rome_control_flow::{builder::BlockId, ExceptionHandlerKind};
use rome_js_syntax::{JsCatchClause, JsFinallyClause, JsTryFinallyStatement, JsTryStatement};
use rome_rowan::{declare_node_union, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
declare_node_union! {
pub(in crate::control_flow) AnyJsTryStatement = JsTryStatement | JsTryFinallyStatement
}
pub(in crate::control_flow) struct TryVisitor {
catch_block: Option<BlockId>,
finally_block: Option<BlockId>,
next_block: BlockId,
}
impl NodeVisitor for TryVisitor {
type Node = AnyJsTryStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
let (has_catch, has_finally) = match node {
AnyJsTryStatement::JsTryStatement(_) => (true, false),
AnyJsTryStatement::JsTryFinallyStatement(node) => (node.catch_clause().is_some(), true),
};
let next_block = builder.append_block();
let finally_block = if has_finally {
let finally_block = builder.append_block();
builder.push_exception_target(ExceptionHandlerKind::Finally, finally_block);
Some(finally_block)
} else {
None
};
let catch_block = if has_catch {
let catch_block = builder.append_block();
builder.push_exception_target(ExceptionHandlerKind::Catch, catch_block);
Some(catch_block)
} else {
None
};
// Create the actual try block (with the exception target set), append
// an implicit jump to it and move the cursor there
let try_block = builder.append_block();
builder.append_jump(false, try_block);
builder.set_cursor(try_block);
Ok(Self {
catch_block,
finally_block,
next_block,
})
}
}
pub(in crate::control_flow) struct CatchVisitor;
impl NodeVisitor for CatchVisitor {
type Node = JsCatchClause;
fn enter(
_: Self::Node,
builder: &mut FunctionBuilder,
stack: StatementStack,
) -> SyntaxResult<Self> {
let try_stmt = stack.read_top::<TryVisitor>()?;
// Insert an implicit jump from the end of the `try` block to the
// `finally` block if it exists, or to the `next` block otherwise
builder.append_jump(false, try_stmt.finally_block.unwrap_or(try_stmt.next_block));
// Pop the catch block from the exception stack
builder.pop_exception_target();
// SAFETY: This block should have been created by the `TryVisitor`
let catch_block = try_stmt.catch_block.unwrap();
builder.set_cursor(catch_block);
Ok(Self)
}
fn exit(
self,
_: Self::Node,
builder: &mut FunctionBuilder,
stack: StatementStack,
) -> SyntaxResult<()> {
let try_stmt = stack.read_top::<TryVisitor>()?;
// Implicit jump from the end of the catch block to the finally block
// (if it exists), or to the next block otherwise
let next_block = try_stmt.finally_block.unwrap_or(try_stmt.next_block);
builder.append_jump(false, next_block);
builder.set_cursor(next_block);
Ok(())
}
}
pub(in crate::control_flow) struct FinallyVisitor;
impl NodeVisitor for FinallyVisitor {
type Node = JsFinallyClause;
fn enter(
_: Self::Node,
builder: &mut FunctionBuilder,
stack: StatementStack,
) -> SyntaxResult<Self> {
let try_stmt = stack.read_top::<TryVisitor>()?;
// SAFETY: This block should have been created by the `TryVisitor`
let finally_block = try_stmt.finally_block.unwrap();
// If the try statement has no catch clause
if try_stmt.catch_block.is_none() {
// Insert an implicit jump from the end of the try block to the
// `finally` block
builder.append_jump(false, finally_block);
// Move the cursor to the finally block (this has already been done
// by the `CatchVisitor` if the try statement has a catch clause)
builder.set_cursor(finally_block);
}
// Pop the finally block from the exception stack
builder.pop_exception_target();
Ok(Self)
}
fn exit(
self,
_: Self::Node,
builder: &mut FunctionBuilder,
stack: StatementStack,
) -> SyntaxResult<()> {
let try_stmt = stack.read_top::<TryVisitor>()?;
// Implicit jump from the end of the finally block to the next block
builder.append_finally_fallthrough(try_stmt.next_block);
builder.set_cursor(try_stmt.next_block);
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/control_flow/nodes/statement.rs | crates/rome_js_analyze/src/control_flow/nodes/statement.rs | use rome_js_syntax::{JsDebuggerStatement, JsEmptyStatement, JsExpressionStatement};
use rome_rowan::{declare_node_union, AstNode, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
declare_node_union! {
pub(in crate::control_flow) JsSimpleStatement = JsDebuggerStatement | JsEmptyStatement | JsExpressionStatement
}
pub(in crate::control_flow) struct StatementVisitor;
impl NodeVisitor for StatementVisitor {
type Node = JsSimpleStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
builder.append_statement().with_node(node.into_syntax());
Ok(Self)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/control_flow/nodes/while_stmt.rs | crates/rome_js_analyze/src/control_flow/nodes/while_stmt.rs | use rome_control_flow::builder::BlockId;
use rome_js_syntax::{JsLabeledStatement, JsSyntaxToken, JsWhileStatement};
use rome_rowan::{AstNode, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
pub(in crate::control_flow) struct WhileVisitor {
// `label`, `continue_block` and `break_block` are used by the
// `ContinueVisitor` and `BreakVisitor`
pub(super) label: Option<JsSyntaxToken>,
pub(super) continue_block: BlockId,
pub(super) break_block: BlockId,
loop_block: BlockId,
}
impl NodeVisitor for WhileVisitor {
type Node = JsWhileStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
// Create the continue and break blocks
let continue_block = builder.append_block();
let break_block = builder.append_block();
// Unconditionally jump to the continue block
builder.append_jump(false, continue_block);
// Create the loop block and fill it with the loop body statement
let loop_block = builder.append_block();
builder.set_cursor(loop_block);
let label = node
.parent::<JsLabeledStatement>()
.and_then(|label| label.label_token().ok());
Ok(Self {
label,
continue_block,
break_block,
loop_block,
})
}
fn exit(
self,
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<()> {
let Self {
continue_block,
break_block,
loop_block,
..
} = self;
// Insert an unconditional jump to the continue block at the end of the loop body
builder.append_jump(false, continue_block);
// Write the continue block
builder.set_cursor(continue_block);
builder
.append_jump(true, loop_block)
.with_node(node.test()?.into_syntax());
builder.append_jump(false, break_block);
// Set the cursor to the break block and move of to the next statement
builder.set_cursor(break_block);
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/control_flow/nodes/return_stmt.rs | crates/rome_js_analyze/src/control_flow/nodes/return_stmt.rs | use rome_js_syntax::JsReturnStatement;
use rome_rowan::{AstNode, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
pub(in crate::control_flow) struct ReturnVisitor;
impl NodeVisitor for ReturnVisitor {
type Node = JsReturnStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
builder.append_return().with_node(node.into_syntax());
Ok(Self)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/control_flow/nodes/continue_stmt.rs | crates/rome_js_analyze/src/control_flow/nodes/continue_stmt.rs | use std::any::TypeId;
use rome_js_syntax::JsContinueStatement;
use rome_rowan::{AstNode, SyntaxError, SyntaxResult};
use crate::control_flow::{
nodes::{DoWhileVisitor, ForInVisitor, ForOfVisitor, ForVisitor, WhileVisitor},
visitor::{FunctionVisitor, NodeVisitor, StatementStack, VisitorAdapter},
FunctionBuilder,
};
pub(in crate::control_flow) struct ContinueVisitor;
impl NodeVisitor for ContinueVisitor {
type Node = JsContinueStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
state: StatementStack,
) -> SyntaxResult<Self> {
let label = node.label_token();
let continue_block = state
.stack
.iter()
.rev()
.take_while(|(type_id, _)| *type_id != TypeId::of::<VisitorAdapter<FunctionVisitor>>())
.find_map(|(type_id, index)| {
let (block_label, block) = if let Some(visitor) =
state.try_downcast::<ForVisitor>(*type_id, *index)
{
(visitor.label.as_ref(), visitor.continue_block)
} else if let Some(visitor) = state.try_downcast::<ForInVisitor>(*type_id, *index) {
(visitor.label.as_ref(), visitor.continue_block)
} else if let Some(visitor) = state.try_downcast::<ForOfVisitor>(*type_id, *index) {
(visitor.label.as_ref(), visitor.continue_block)
} else if let Some(visitor) = state.try_downcast::<WhileVisitor>(*type_id, *index) {
(visitor.label.as_ref(), visitor.continue_block)
} else if let Some(visitor) = state.try_downcast::<DoWhileVisitor>(*type_id, *index)
{
(visitor.label.as_ref(), visitor.continue_block)
} else {
return None;
};
match (block_label, &label) {
(Some(a), Some(b)) => {
if a.text_trimmed() == b.text_trimmed() {
Some(block)
} else {
None
}
}
(None, None) => Some(block),
_ => None,
}
})
.ok_or(SyntaxError::MissingRequiredChild)?;
builder
.append_jump(false, continue_block)
.with_node(node.into_syntax());
Ok(Self)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/control_flow/nodes/for_in.rs | crates/rome_js_analyze/src/control_flow/nodes/for_in.rs | use rome_control_flow::builder::BlockId;
use rome_js_syntax::{JsForInStatement, JsLabeledStatement, JsSyntaxToken};
use rome_rowan::{AstNode, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
pub(in crate::control_flow) struct ForInVisitor {
// `label`, `continue_block` and `break_block` are used by the
// `ContinueVisitor` and `BreakVisitor`
pub(super) label: Option<JsSyntaxToken>,
pub(super) continue_block: BlockId,
pub(super) break_block: BlockId,
}
impl NodeVisitor for ForInVisitor {
type Node = JsForInStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
let continue_block = builder.append_block();
let loop_block = builder.append_block();
let break_block = builder.append_block();
builder.append_jump(false, continue_block);
builder.set_cursor(continue_block);
builder
.append_jump(true, loop_block)
.with_node(node.initializer()?.into_syntax());
builder.append_jump(false, break_block);
let label = node
.parent::<JsLabeledStatement>()
.and_then(|label| label.label_token().ok());
builder.set_cursor(loop_block);
Ok(Self {
label,
continue_block,
break_block,
})
}
fn exit(
self,
_: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<()> {
let Self {
continue_block,
break_block,
..
} = self;
builder.append_jump(false, continue_block);
builder.set_cursor(break_block);
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/control_flow/nodes/for_of.rs | crates/rome_js_analyze/src/control_flow/nodes/for_of.rs | use rome_control_flow::builder::BlockId;
use rome_js_syntax::{JsForOfStatement, JsLabeledStatement, JsSyntaxToken};
use rome_rowan::{AstNode, SyntaxResult};
use crate::control_flow::{
visitor::{NodeVisitor, StatementStack},
FunctionBuilder,
};
pub(in crate::control_flow) struct ForOfVisitor {
// `label`, `continue_block` and `break_block` are used by the
// `ContinueVisitor` and `BreakVisitor`
pub(super) label: Option<JsSyntaxToken>,
pub(super) continue_block: BlockId,
pub(super) break_block: BlockId,
}
impl NodeVisitor for ForOfVisitor {
type Node = JsForOfStatement;
fn enter(
node: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<Self> {
let continue_block = builder.append_block();
let loop_block = builder.append_block();
let break_block = builder.append_block();
builder.append_jump(false, continue_block);
builder.set_cursor(continue_block);
builder
.append_jump(true, loop_block)
.with_node(node.initializer()?.into_syntax());
builder.append_jump(false, break_block);
let label = node
.parent::<JsLabeledStatement>()
.and_then(|label| label.label_token().ok());
builder.set_cursor(loop_block);
Ok(Self {
label,
continue_block,
break_block,
})
}
fn exit(
self,
_: Self::Node,
builder: &mut FunctionBuilder,
_: StatementStack,
) -> SyntaxResult<()> {
let Self {
continue_block,
break_block,
..
} = self;
builder.append_jump(false, continue_block);
builder.set_cursor(break_block);
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/react/hooks.rs | crates/rome_js_analyze/src/react/hooks.rs | use crate::react::{is_react_call_api, ReactLibrary};
use std::collections::{HashMap, HashSet};
use rome_js_semantic::{Capture, Closure, ClosureExtensions, SemanticModel};
use rome_js_syntax::{
binding_ext::AnyJsIdentifierBinding, static_value::StaticValue, AnyJsExpression,
AnyJsMemberExpression, JsArrayBindingPattern, JsArrayBindingPatternElementList,
JsArrowFunctionExpression, JsCallExpression, JsFunctionExpression, JsVariableDeclarator,
TextRange,
};
use rome_rowan::AstNode;
use serde::{Deserialize, Serialize};
/// Return result of [react_hook_with_dependency].
pub(crate) struct ReactCallWithDependencyResult {
pub(crate) function_name_range: TextRange,
pub(crate) closure_node: Option<AnyJsExpression>,
pub(crate) dependencies_node: Option<AnyJsExpression>,
}
pub enum AnyJsFunctionExpression {
JsArrowFunctionExpression(JsArrowFunctionExpression),
JsFunctionExpression(JsFunctionExpression),
}
impl AnyJsFunctionExpression {
fn closure(&self, model: &SemanticModel) -> Closure {
match self {
Self::JsArrowFunctionExpression(arrow_function) => arrow_function.closure(model),
Self::JsFunctionExpression(function) => function.closure(model),
}
}
}
impl TryFrom<AnyJsExpression> for AnyJsFunctionExpression {
type Error = ();
fn try_from(expression: AnyJsExpression) -> Result<Self, Self::Error> {
match expression {
AnyJsExpression::JsArrowFunctionExpression(arrow_function) => {
Ok(Self::JsArrowFunctionExpression(arrow_function))
}
AnyJsExpression::JsFunctionExpression(function) => {
Ok(Self::JsFunctionExpression(function))
}
_ => Err(()),
}
}
}
impl ReactCallWithDependencyResult {
/// Returns all [Reference] captured by the closure argument of the React hook.
/// See [react_hook_with_dependency].
pub fn all_captures(&self, model: &SemanticModel) -> impl Iterator<Item = Capture> {
self.closure_node
.as_ref()
.and_then(|node| AnyJsFunctionExpression::try_from(node.clone()).ok())
.map(|function_expression| {
let closure = function_expression.closure(model);
let range = *closure.closure_range();
closure
.descendents()
.flat_map(|closure| closure.all_captures())
.filter(move |capture| capture.declaration_range().intersect(range).is_none())
})
.into_iter()
.flatten()
}
/// Returns all dependencies of a React hook.
/// See [react_hook_with_dependency]
pub fn all_dependencies(&self) -> impl Iterator<Item = AnyJsExpression> {
self.dependencies_node
.as_ref()
.and_then(|x| Some(x.as_js_array_expression()?.elements().into_iter()))
.into_iter()
.flatten()
.filter_map(|x| x.ok()?.as_any_js_expression().cloned())
}
}
#[derive(Default, Debug, Copy, Clone, Serialize, Deserialize)]
pub struct ReactHookConfiguration {
pub closure_index: Option<usize>,
pub dependencies_index: Option<usize>,
}
impl From<(usize, usize)> for ReactHookConfiguration {
fn from((closure, dependencies): (usize, usize)) -> Self {
Self {
closure_index: Some(closure),
dependencies_index: Some(dependencies),
}
}
}
pub(crate) fn react_hook_configuration<'a>(
call: &JsCallExpression,
hooks: &'a HashMap<String, ReactHookConfiguration>,
) -> Option<&'a ReactHookConfiguration> {
let name = call
.callee()
.ok()?
.as_js_identifier_expression()?
.name()
.ok()?
.value_token()
.ok()?;
let name = name.text_trimmed();
hooks.get(name)
}
const HOOKS_WITH_DEPS_API: [&str; 6] = [
"useEffect",
"useLayoutEffect",
"useInsertionEffect",
"useCallback",
"useMemo",
"useImperativeHandle",
];
/// Returns the [TextRange] of the hook name; the node of the
/// expression of the argument that correspond to the closure of
/// the hook; and the node of the dependency list of the hook.
///
/// Example:
/// ```js
/// useEffect(() => {}, []);
/// ^^ <- dependencies_node
/// ^^^^^^^^ <- closure_node
/// ^^^^^^^^^ <- function_name_range
/// ```
///
/// This function will use the parameter "hooks" with the configuration
/// of all function that are considered hooks. See [ReactHookConfiguration].
pub(crate) fn react_hook_with_dependency(
call: &JsCallExpression,
hooks: &HashMap<String, ReactHookConfiguration>,
model: &SemanticModel,
) -> Option<ReactCallWithDependencyResult> {
let expression = call.callee().ok()?;
let name = if let Some(identifier) = expression.as_js_reference_identifier() {
Some(StaticValue::String(identifier.value_token().ok()?))
} else if let Some(member_expr) = AnyJsMemberExpression::cast_ref(expression.syntax()) {
Some(member_expr.member_name()?)
} else {
None
}?;
let function_name_range = name.range();
let name = name.text();
// check if the hooks api is imported from the react library
if HOOKS_WITH_DEPS_API.contains(&name)
&& !is_react_call_api(expression, model, ReactLibrary::React, name)
{
return None;
}
let hook = hooks.get(name)?;
let closure_index = hook.closure_index?;
let dependencies_index = hook.dependencies_index?;
let mut indices = [closure_index, dependencies_index];
indices.sort();
let [closure_node, dependencies_node] = call.get_arguments_by_index(indices);
Some(ReactCallWithDependencyResult {
function_name_range,
closure_node: closure_node.and_then(|x| x.as_any_js_expression().cloned()),
dependencies_node: dependencies_node.and_then(|x| x.as_any_js_expression().cloned()),
})
}
/// Specifies which, if any, of the returns of a React hook are stable.
/// See [is_binding_react_stable].
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct StableReactHookConfiguration {
/// Name of the React hook
hook_name: String,
/// Index of the position of the stable return, [None] if
/// none returns are stable
index: Option<usize>,
}
impl StableReactHookConfiguration {
pub fn new(hook_name: &str, index: Option<usize>) -> Self {
Self {
hook_name: hook_name.into(),
index,
}
}
}
/// Checks if the binding is bound to a stable React hook
/// return value. Stable returns do not need to be specified
/// as dependencies.
///
/// Example:
/// ```js
/// let [name, setName] = useState("");
/// useEffect(() => {
/// // name is NOT stable, so it must be specified as dependency
/// console.log(name);
/// // setName IS stable, so it must not be specified as dependency
/// console.log(setName("a"));
/// }, [name]);
/// ```
pub fn is_binding_react_stable(
binding: &AnyJsIdentifierBinding,
stable_config: &HashSet<StableReactHookConfiguration>,
) -> bool {
fn array_binding_declarator_index(
binding: &AnyJsIdentifierBinding,
) -> Option<(JsVariableDeclarator, Option<usize>)> {
let index = binding.syntax().index() / 2;
let declarator = binding
.parent::<JsArrayBindingPatternElementList>()?
.parent::<JsArrayBindingPattern>()?
.parent::<JsVariableDeclarator>()?;
Some((declarator, Some(index)))
}
fn assignment_declarator(
binding: &AnyJsIdentifierBinding,
) -> Option<(JsVariableDeclarator, Option<usize>)> {
let declarator = binding.parent::<JsVariableDeclarator>()?;
Some((declarator, None))
}
array_binding_declarator_index(binding)
.or_else(|| assignment_declarator(binding))
.and_then(|(declarator, index)| {
let hook_name = declarator
.initializer()?
.expression()
.ok()?
.as_js_call_expression()?
.callee()
.ok()?
.as_js_identifier_expression()?
.name()
.ok()?
.value_token()
.ok()?
.token_text();
let stable = StableReactHookConfiguration {
hook_name: hook_name.to_string(),
index,
};
Some(stable_config.contains(&stable))
})
.unwrap_or(false)
}
#[cfg(test)]
mod test {
use super::*;
use rome_js_parser::JsParserOptions;
use rome_js_syntax::JsFileSource;
#[test]
pub fn ok_react_stable_captures() {
let r = rome_js_parser::parse(
"const ref = useRef();",
JsFileSource::js_module(),
JsParserOptions::default(),
);
let node = r
.syntax()
.descendants()
.filter(|x| x.text_trimmed() == "ref")
.last()
.unwrap();
let set_name = AnyJsIdentifierBinding::cast(node).unwrap();
let config = HashSet::from_iter([
StableReactHookConfiguration::new("useRef", None),
StableReactHookConfiguration::new("useState", Some(1)),
]);
assert!(is_binding_react_stable(&set_name, &config));
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/tests/spec_tests.rs | crates/rome_js_analyze/tests/spec_tests.rs | use rome_analyze::{AnalysisFilter, AnalyzerAction, ControlFlow, Never, RuleFilter};
use rome_diagnostics::advice::CodeSuggestionAdvice;
use rome_diagnostics::{DiagnosticExt, Severity};
use rome_js_parser::{parse, JsParserOptions};
use rome_js_syntax::{JsFileSource, JsLanguage};
use rome_rowan::AstNode;
use rome_test_utils::{
assert_errors_are_absent, code_fix_to_string, create_analyzer_options, diagnostic_to_string,
has_bogus_nodes_or_empty_slots, parse_test_path, register_leak_checker, scripts_from_json,
write_analyzer_snapshot, CheckActionType,
};
use std::{ffi::OsStr, fs::read_to_string, path::Path, slice};
tests_macros::gen_tests! {"tests/specs/**/*.{cjs,js,jsx,tsx,ts,json,jsonc}", crate::run_test, "module"}
tests_macros::gen_tests! {"tests/suppression/**/*.{cjs,js,jsx,tsx,ts,json,jsonc}", crate::run_suppression_test, "module"}
fn run_test(input: &'static str, _: &str, _: &str, _: &str) {
register_leak_checker();
let input_file = Path::new(input);
let file_name = input_file.file_name().and_then(OsStr::to_str).unwrap();
let (group, rule) = parse_test_path(input_file);
if rule == "specs" || rule == "suppression" {
panic!("the test file must be placed in the {rule}/<group-name>/<rule-name>/ directory");
}
if group == "specs" || group == "suppression" {
panic!("the test file must be placed in the {group}/{rule}/<rule-name>/ directory");
}
if rome_js_analyze::metadata().find_rule(group, rule).is_none() {
panic!("could not find rule {group}/{rule}");
}
let rule_filter = RuleFilter::Rule(group, rule);
let filter = AnalysisFilter {
enabled_rules: Some(slice::from_ref(&rule_filter)),
..AnalysisFilter::default()
};
let mut snapshot = String::new();
let extension = input_file.extension().unwrap_or_default();
let input_code = read_to_string(input_file)
.unwrap_or_else(|err| panic!("failed to read {:?}: {:?}", input_file, err));
let quantity_diagnostics = if let Some(scripts) = scripts_from_json(extension, &input_code) {
for script in scripts {
analyze_and_snap(
&mut snapshot,
&script,
JsFileSource::js_script(),
filter,
file_name,
input_file,
CheckActionType::Lint,
JsParserOptions::default(),
);
}
0
} else {
let Ok(source_type) = input_file.try_into() else {
return;
};
analyze_and_snap(
&mut snapshot,
&input_code,
source_type,
filter,
file_name,
input_file,
CheckActionType::Lint,
JsParserOptions::default(),
)
};
insta::with_settings!({
prepend_module_to_snapshot => false,
snapshot_path => input_file.parent().unwrap(),
}, {
insta::assert_snapshot!(file_name, snapshot, file_name);
});
if input_code.contains("/* should not generate diagnostics */") && quantity_diagnostics > 0 {
panic!("This test should not generate diagnostics");
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn analyze_and_snap(
snapshot: &mut String,
input_code: &str,
source_type: JsFileSource,
filter: AnalysisFilter,
file_name: &str,
input_file: &Path,
check_action_type: CheckActionType,
parser_options: JsParserOptions,
) -> usize {
let parsed = parse(input_code, source_type, parser_options.clone());
let root = parsed.tree();
let mut diagnostics = Vec::new();
let mut code_fixes = Vec::new();
let options = create_analyzer_options(input_file, &mut diagnostics);
let (_, errors) = rome_js_analyze::analyze(&root, filter, &options, source_type, |event| {
if let Some(mut diag) = event.diagnostic() {
for action in event.actions() {
if check_action_type.is_suppression() {
if action.is_suppression() {
check_code_action(
input_file,
input_code,
source_type,
&action,
parser_options.clone(),
);
diag = diag.add_code_suggestion(CodeSuggestionAdvice::from(action));
}
} else if !action.is_suppression() {
check_code_action(
input_file,
input_code,
source_type,
&action,
parser_options.clone(),
);
diag = diag.add_code_suggestion(CodeSuggestionAdvice::from(action));
}
}
let error = diag.with_severity(Severity::Warning);
diagnostics.push(diagnostic_to_string(file_name, input_code, error));
return ControlFlow::Continue(());
}
for action in event.actions() {
if check_action_type.is_suppression() {
if action.category.matches("quickfix.suppressRule") {
check_code_action(
input_file,
input_code,
source_type,
&action,
parser_options.clone(),
);
code_fixes.push(code_fix_to_string(input_code, action));
}
} else if !action.category.matches("quickfix.suppressRule") {
check_code_action(
input_file,
input_code,
source_type,
&action,
parser_options.clone(),
);
code_fixes.push(code_fix_to_string(input_code, action));
}
}
ControlFlow::<Never>::Continue(())
});
for error in errors {
diagnostics.push(diagnostic_to_string(file_name, input_code, error));
}
write_analyzer_snapshot(
snapshot,
input_code,
diagnostics.as_slice(),
code_fixes.as_slice(),
);
diagnostics.len()
}
fn check_code_action(
path: &Path,
source: &str,
source_type: JsFileSource,
action: &AnalyzerAction<JsLanguage>,
options: JsParserOptions,
) {
let (_, text_edit) = action.mutation.as_text_edits().unwrap_or_default();
let output = text_edit.new_string(source);
let new_tree = action.mutation.clone().commit();
// Checks that applying the text edits returned by the BatchMutation
// returns the same code as printing the modified syntax tree
assert_eq!(new_tree.to_string(), output);
if has_bogus_nodes_or_empty_slots(&new_tree) {
panic!(
"modified tree has bogus nodes or empty slots:\n{new_tree:#?} \n\n {}",
new_tree
)
}
// Checks the returned tree contains no missing children node
if format!("{new_tree:?}").contains("missing (required)") {
panic!("modified tree has missing children:\n{new_tree:#?}")
}
// Re-parse the modified code and panic if the resulting tree has syntax errors
let re_parse = parse(&output, source_type, options);
assert_errors_are_absent(re_parse.tree().syntax(), re_parse.diagnostics(), path);
}
pub(crate) fn run_suppression_test(input: &'static str, _: &str, _: &str, _: &str) {
register_leak_checker();
let input_file = Path::new(input);
let file_name = input_file.file_name().and_then(OsStr::to_str).unwrap();
let input_code = read_to_string(input_file)
.unwrap_or_else(|err| panic!("failed to read {:?}: {:?}", input_file, err));
let (group, rule) = parse_test_path(input_file);
let rule_filter = RuleFilter::Rule(group, rule);
let filter = AnalysisFilter {
enabled_rules: Some(slice::from_ref(&rule_filter)),
..AnalysisFilter::default()
};
let mut snapshot = String::new();
analyze_and_snap(
&mut snapshot,
&input_code,
JsFileSource::jsx(),
filter,
file_name,
input_file,
CheckActionType::Suppression,
JsParserOptions::default(),
);
insta::with_settings!({
prepend_module_to_snapshot => false,
snapshot_path => input_file.parent().unwrap(),
}, {
insta::assert_snapshot!(file_name, snapshot, file_name);
});
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/diagnostics.rs | crates/rome_analyze/src/diagnostics.rs | use rome_console::MarkupBuf;
use rome_diagnostics::{
advice::CodeSuggestionAdvice, category, Advices, Category, Diagnostic, DiagnosticExt,
DiagnosticTags, Error, Location, Severity, Visit,
};
use rome_rowan::TextRange;
use std::fmt::{Debug, Display, Formatter};
use crate::rule::RuleDiagnostic;
/// Small wrapper for diagnostics during the analysis phase.
///
/// During these phases, analyzers can create various type diagnostics and some of them
/// don't have all the info to actually create a real [Diagnostic].
///
/// This wrapper serves as glue, which eventually is able to spit out full fledged diagnostics.
///
#[derive(Debug)]
pub struct AnalyzerDiagnostic {
kind: DiagnosticKind,
/// Series of code suggestions offered by rule code actions
code_suggestion_list: Vec<CodeSuggestionAdvice<MarkupBuf>>,
}
impl From<RuleDiagnostic> for AnalyzerDiagnostic {
fn from(rule_diagnostic: RuleDiagnostic) -> Self {
Self {
kind: DiagnosticKind::Rule(rule_diagnostic),
code_suggestion_list: vec![],
}
}
}
#[derive(Debug)]
enum DiagnosticKind {
/// It holds various info related to diagnostics emitted by the rules
Rule(RuleDiagnostic),
/// We have raw information to create a basic [Diagnostic]
Raw(Error),
}
impl Diagnostic for AnalyzerDiagnostic {
fn category(&self) -> Option<&'static Category> {
match &self.kind {
DiagnosticKind::Rule(rule_diagnostic) => Some(rule_diagnostic.category),
DiagnosticKind::Raw(error) => error.category(),
}
}
fn description(&self, fmt: &mut Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DiagnosticKind::Rule(rule_diagnostic) => Debug::fmt(&rule_diagnostic.message, fmt),
DiagnosticKind::Raw(error) => error.description(fmt),
}
}
fn message(&self, fmt: &mut rome_console::fmt::Formatter<'_>) -> std::io::Result<()> {
match &self.kind {
DiagnosticKind::Rule(rule_diagnostic) => {
rome_console::fmt::Display::fmt(&rule_diagnostic.message, fmt)
}
DiagnosticKind::Raw(error) => error.message(fmt),
}
}
fn severity(&self) -> Severity {
match &self.kind {
DiagnosticKind::Rule { .. } => Severity::Error,
DiagnosticKind::Raw(error) => error.severity(),
}
}
fn tags(&self) -> DiagnosticTags {
match &self.kind {
DiagnosticKind::Rule(rule_diagnostic) => rule_diagnostic.tags,
DiagnosticKind::Raw(error) => error.tags(),
}
}
fn location(&self) -> Location<'_> {
match &self.kind {
DiagnosticKind::Rule(rule_diagnostic) => {
Location::builder().span(&rule_diagnostic.span).build()
}
DiagnosticKind::Raw(error) => error.location(),
}
}
fn advices(&self, visitor: &mut dyn Visit) -> std::io::Result<()> {
match &self.kind {
DiagnosticKind::Rule(rule_diagnostic) => rule_diagnostic.advices().record(visitor)?,
DiagnosticKind::Raw(error) => error.advices(visitor)?,
}
// finally, we print possible code suggestions on how to fix the issue
for suggestion in &self.code_suggestion_list {
suggestion.record(visitor)?;
}
Ok(())
}
}
impl AnalyzerDiagnostic {
/// Creates a diagnostic from a generic [Error]
pub fn from_error(error: Error) -> Self {
Self {
kind: DiagnosticKind::Raw(error),
code_suggestion_list: vec![],
}
}
pub fn get_span(&self) -> Option<TextRange> {
match &self.kind {
DiagnosticKind::Rule(rule_diagnostic) => rule_diagnostic.span,
DiagnosticKind::Raw(error) => error.location().span,
}
}
/// It adds a code suggestion, use this API to tell the user that a rule can benefit from
/// a automatic code fix.
pub fn add_code_suggestion(mut self, suggestion: CodeSuggestionAdvice<MarkupBuf>) -> Self {
self.kind = match self.kind {
DiagnosticKind::Rule(mut rule_diagnostic) => {
rule_diagnostic.tags = DiagnosticTags::FIXABLE;
DiagnosticKind::Rule(rule_diagnostic)
}
DiagnosticKind::Raw(error) => {
DiagnosticKind::Raw(error.with_tags(DiagnosticTags::FIXABLE))
}
};
self.code_suggestion_list.push(suggestion);
self
}
pub const fn is_raw(&self) -> bool {
matches!(self.kind, DiagnosticKind::Raw(_))
}
}
#[derive(Debug, Diagnostic)]
#[diagnostic(severity = Warning)]
pub(crate) struct SuppressionDiagnostic {
#[category]
category: &'static Category,
#[location(span)]
range: TextRange,
#[message]
#[description]
message: String,
#[tags]
tags: DiagnosticTags,
}
impl SuppressionDiagnostic {
pub(crate) fn new(
category: &'static Category,
range: TextRange,
message: impl Display,
) -> Self {
Self {
category,
range,
message: message.to_string(),
tags: DiagnosticTags::empty(),
}
}
pub(crate) fn with_tags(mut self, tags: DiagnosticTags) -> Self {
self.tags |= tags;
self
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/visitor.rs | crates/rome_analyze/src/visitor.rs | use crate::{
matcher::{MatchQueryParams, Query},
registry::{NodeLanguage, Phases},
AnalyzerOptions, LanguageRoot, QueryMatch, QueryMatcher, ServiceBag, SignalEntry,
SuppressionCommentEmitter,
};
use rome_rowan::{AstNode, Language, SyntaxNode, TextRange, WalkEvent};
use std::collections::BinaryHeap;
/// Mutable context objects shared by all visitors
pub struct VisitorContext<'phase, 'query, L: Language> {
pub phase: Phases,
pub root: &'phase LanguageRoot<L>,
pub services: &'phase ServiceBag,
pub range: Option<TextRange>,
pub(crate) query_matcher: &'query mut dyn QueryMatcher<L>,
pub(crate) signal_queue: &'query mut BinaryHeap<SignalEntry<'phase, L>>,
pub apply_suppression_comment: SuppressionCommentEmitter<L>,
pub options: &'phase AnalyzerOptions,
}
impl<'phase, 'query, L: Language> VisitorContext<'phase, 'query, L> {
pub fn match_query<T: QueryMatch>(&mut self, query: T) {
self.query_matcher.match_query(MatchQueryParams {
phase: self.phase,
root: self.root,
query: Query::new(query),
services: self.services,
signal_queue: self.signal_queue,
apply_suppression_comment: self.apply_suppression_comment,
options: self.options,
})
}
}
/// Mutable context objects provided to the finish hook of visitors
pub struct VisitorFinishContext<'a, L: Language> {
pub root: &'a LanguageRoot<L>,
pub services: &'a mut ServiceBag,
}
/// Visitors are the main building blocks of the analyzer: they receive syntax
/// [WalkEvent]s, process these events to build secondary data structures from
/// the syntax tree, and emit rule query matches through the [crate::RuleRegistry]
pub trait Visitor {
type Language: Language;
fn visit(
&mut self,
event: &WalkEvent<SyntaxNode<Self::Language>>,
ctx: VisitorContext<Self::Language>,
);
fn finish(self: Box<Self>, ctx: VisitorFinishContext<Self::Language>) {
let _ = ctx;
}
}
/// A node visitor is a special kind of visitor that does not have a persistent
/// state for the entire run of the analyzer. Instead these visitors are
/// transient, they get instantiated when the traversal enters the
/// corresponding node type and destroyed when the corresponding node exits
///
/// Due to these specificities node visitors do not implement [Visitor]
/// directly, instead one or more of these must the merged into a single
/// visitor type using the [crate::merge_node_visitors] macro
pub trait NodeVisitor<V>: Sized {
type Node: AstNode;
fn enter(
node: Self::Node,
ctx: &mut VisitorContext<NodeLanguage<Self::Node>>,
stack: &mut V,
) -> Self;
fn exit(
self,
node: Self::Node,
ctx: &mut VisitorContext<NodeLanguage<Self::Node>>,
stack: &mut V,
);
}
/// Creates a single struct implementing [Visitor] over a collection of type
/// implementing the [NodeVisitor] helper trait. Unlike the global [Visitor],
/// node visitors are transient: they get instantiated when the traversal
/// enters the corresponding node and destroyed when the node is exited. They
/// are intended as a building blocks for creating and managing the state of
/// complex visitors by allowing the implementation to be split over multiple
/// smaller components.
///
/// # Example
///
/// ```ignore
/// struct BinaryVisitor;
///
/// impl NodeVisitor for BinaryVisitor {
/// type Node = BinaryExpression;
/// }
///
/// struct UnaryVisitor;
///
/// impl NodeVisitor for UnaryVisitor {
/// type Node = UnaryExpression;
/// }
///
/// merge_node_visitors! {
/// // This declares a new `ExpressionVisitor` struct that implements
/// // `Visitor` and manages instances of `BinaryVisitor` and
/// // `UnaryVisitor`
/// pub(crate) ExpressionVisitor {
/// binary: BinaryVisitor,
/// unary: UnaryVisitor,
/// }
/// }
/// ```
#[macro_export]
macro_rules! merge_node_visitors {
( $vis:vis $name:ident { $( $id:ident: $visitor:ty, )+ } ) => {
$vis struct $name {
stack: Vec<(::std::any::TypeId, usize)>,
$( $vis $id: Vec<(usize, $visitor)>, )*
}
impl $name {
$vis fn new() -> Self {
Self {
stack: Vec::new(),
$( $id: Vec::new(), )*
}
}
}
impl $crate::Visitor for $name {
type Language = <( $( <$visitor as $crate::NodeVisitor<$name>>::Node, )* ) as ::rome_rowan::macros::UnionLanguage>::Language;
fn visit(
&mut self,
event: &::rome_rowan::WalkEvent<::rome_rowan::SyntaxNode<Self::Language>>,
mut ctx: $crate::VisitorContext<Self::Language>,
) {
match event {
::rome_rowan::WalkEvent::Enter(node) => {
let kind = node.kind();
$(
if <<$visitor as $crate::NodeVisitor<$name>>::Node as ::rome_rowan::AstNode>::can_cast(kind) {
let node = <<$visitor as $crate::NodeVisitor<$name>>::Node as ::rome_rowan::AstNode>::unwrap_cast(node.clone());
let state = <$visitor as $crate::NodeVisitor<$name>>::enter(node, &mut ctx, self);
let stack_index = self.stack.len();
let ty_index = self.$id.len();
self.$id.push((stack_index, state));
self.stack.push((::std::any::TypeId::of::<$visitor>(), ty_index));
return;
}
)*
}
::rome_rowan::WalkEvent::Leave(node) => {
let kind = node.kind();
$(
if <<$visitor as $crate::NodeVisitor<$name>>::Node as ::rome_rowan::AstNode>::can_cast(kind) {
self.stack.pop().unwrap();
let (_, state) = self.$id.pop().unwrap();
let node = <<$visitor as $crate::NodeVisitor<$name>>::Node as ::rome_rowan::AstNode>::unwrap_cast(node.clone());
<$visitor as $crate::NodeVisitor<$name>>::exit(state, node, &mut ctx, self);
return;
}
)*
}
}
}
}
};
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/services.rs | crates/rome_analyze/src/services.rs | use crate::{RuleKey, TextRange};
use rome_diagnostics::{Diagnostic, LineIndexBuf, Resource, Result, SourceCode};
use std::{
any::{Any, TypeId},
collections::HashMap,
};
#[derive(Debug, Diagnostic)]
#[diagnostic(category = "internalError/io", tags(INTERNAL))]
pub struct MissingServicesDiagnostic {
#[message]
message: String,
#[description]
description: String,
#[location(resource)]
path: Resource<&'static str>,
#[location(span)]
span: Option<TextRange>,
#[location(source_code)]
source_code: Option<SourceCode<String, LineIndexBuf>>,
}
impl MissingServicesDiagnostic {
pub fn new(rule_name: &str, missing_services: &'static [&'static str]) -> Self {
let description = missing_services.join(", ");
Self {
message: format!("Errors emitted while attempting run the rule: {rule_name}"),
description: format!("Missing services: {description}"),
source_code: None,
path: Resource::Memory,
span: None,
}
}
}
pub trait FromServices: Sized {
#[allow(clippy::result_large_err)]
fn from_services(
rule_key: &RuleKey,
services: &ServiceBag,
) -> Result<Self, MissingServicesDiagnostic>;
}
#[derive(Debug, Default)]
pub struct ServiceBag {
services: HashMap<TypeId, Box<dyn Any>>,
}
impl ServiceBag {
pub fn insert_service<T: 'static>(&mut self, service: T) {
let id = TypeId::of::<T>();
self.services.insert(id, Box::new(service));
}
pub fn get_service<T: 'static>(&self) -> Option<&T> {
let id = TypeId::of::<T>();
let svc = self.services.get(&id)?;
svc.downcast_ref()
}
}
impl FromServices for () {
fn from_services(_: &RuleKey, _: &ServiceBag) -> Result<Self, MissingServicesDiagnostic> {
Ok(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/lib.rs | crates/rome_analyze/src/lib.rs | #![deny(rustdoc::broken_intra_doc_links)]
#![doc = include_str!("../CONTRIBUTING.md")]
use std::cmp::Ordering;
use std::collections::{BTreeMap, BinaryHeap};
use std::fmt::{Debug, Display, Formatter};
use std::ops;
mod categories;
pub mod context;
mod diagnostics;
mod matcher;
pub mod options;
mod query;
mod registry;
mod rule;
mod services;
mod signals;
mod syntax;
mod visitor;
// Re-exported for use in the `declare_group` macro
pub use rome_diagnostics::category_concat;
pub use crate::categories::{
ActionCategory, RefactorKind, RuleCategories, RuleCategory, SourceActionKind,
};
pub use crate::diagnostics::AnalyzerDiagnostic;
use crate::diagnostics::SuppressionDiagnostic;
pub use crate::matcher::{InspectMatcher, MatchQueryParams, QueryMatcher, RuleKey, SignalEntry};
pub use crate::options::{AnalyzerConfiguration, AnalyzerOptions, AnalyzerRules};
pub use crate::query::{AddVisitor, QueryKey, QueryMatch, Queryable};
pub use crate::registry::{
LanguageRoot, MetadataRegistry, Phase, Phases, RegistryRuleMetadata, RegistryVisitor,
RuleRegistry, RuleRegistryBuilder, RuleSuppressions,
};
pub use crate::rule::{
CategoryLanguage, GroupCategory, GroupLanguage, Rule, RuleAction, RuleDiagnostic, RuleGroup,
RuleMeta, RuleMetadata, SuppressAction,
};
pub use crate::services::{FromServices, MissingServicesDiagnostic, ServiceBag};
pub use crate::signals::{
AnalyzerAction, AnalyzerSignal, AnalyzerTransformation, DiagnosticSignal,
};
pub use crate::syntax::{Ast, SyntaxVisitor};
pub use crate::visitor::{NodeVisitor, Visitor, VisitorContext, VisitorFinishContext};
use rome_console::markup;
use rome_diagnostics::{category, Applicability, Diagnostic, DiagnosticExt, DiagnosticTags};
use rome_rowan::{
AstNode, BatchMutation, Direction, Language, SyntaxElement, SyntaxToken, TextRange, TextSize,
TokenAtOffset, TriviaPieceKind, WalkEvent,
};
/// The analyzer is the main entry point into the `rome_analyze` infrastructure.
/// Its role is to run a collection of [Visitor]s over a syntax tree, with each
/// visitor implementing various analysis over this syntax tree to generate
/// auxiliary data structures as well as emit "query match" events to be
/// processed by lint rules and in turn emit "analyzer signals" in the form of
/// diagnostics, code actions or both
pub struct Analyzer<'analyzer, L: Language, Matcher, Break, Diag> {
/// List of visitors being run by this instance of the analyzer for each phase
phases: BTreeMap<Phases, Vec<Box<dyn Visitor<Language = L> + 'analyzer>>>,
/// Holds the metadata for all the rules statically known to the analyzer
metadata: &'analyzer MetadataRegistry,
/// Executor for the query matches emitted by the visitors
query_matcher: Matcher,
/// Language-specific suppression comment parsing function
parse_suppression_comment: SuppressionParser<Diag>,
/// Language-specific suppression comment emitter
apply_suppression_comment: SuppressionCommentEmitter<L>,
/// Handles analyzer signals emitted by individual rules
emit_signal: SignalHandler<'analyzer, L, Break>,
}
pub struct AnalyzerContext<'a, L: Language> {
pub root: LanguageRoot<L>,
pub services: ServiceBag,
pub range: Option<TextRange>,
pub options: &'a AnalyzerOptions,
}
impl<'analyzer, L, Matcher, Break, Diag> Analyzer<'analyzer, L, Matcher, Break, Diag>
where
L: Language,
Matcher: QueryMatcher<L>,
Diag: Diagnostic + Clone + Send + Sync + 'static,
{
/// Construct a new instance of the analyzer with the given rule registry
/// and suppression comment parser
pub fn new(
metadata: &'analyzer MetadataRegistry,
query_matcher: Matcher,
parse_suppression_comment: SuppressionParser<Diag>,
apply_suppression_comment: SuppressionCommentEmitter<L>,
emit_signal: SignalHandler<'analyzer, L, Break>,
) -> Self {
Self {
phases: BTreeMap::new(),
metadata,
query_matcher,
parse_suppression_comment,
apply_suppression_comment,
emit_signal,
}
}
/// Registers a [Visitor] to be executed as part of a given `phase` of the analyzer run
pub fn add_visitor(
&mut self,
phase: Phases,
visitor: Box<dyn Visitor<Language = L> + 'analyzer>,
) {
self.phases.entry(phase).or_default().push(visitor);
}
pub fn run(self, mut ctx: AnalyzerContext<L>) -> Option<Break> {
let Self {
phases,
metadata,
mut query_matcher,
parse_suppression_comment,
mut emit_signal,
apply_suppression_comment,
} = self;
let mut line_index = 0;
let mut line_suppressions = Vec::new();
for (index, (phase, mut visitors)) in phases.into_iter().enumerate() {
let runner = PhaseRunner {
phase,
visitors: &mut visitors,
metadata,
query_matcher: &mut query_matcher,
signal_queue: BinaryHeap::new(),
parse_suppression_comment,
line_index: &mut line_index,
line_suppressions: &mut line_suppressions,
emit_signal: &mut emit_signal,
root: &ctx.root,
services: &ctx.services,
range: ctx.range,
apply_suppression_comment,
options: ctx.options,
};
// The first phase being run will inspect the tokens and parse the
// suppression comments, then subsequent phases only needs to read
// this data again since it's already cached in `line_suppressions`
let result = if index == 0 {
runner.run_first_phase()
} else {
runner.run_remaining_phases()
};
if let ControlFlow::Break(br) = result {
return Some(br);
}
// Finish all the active visitors, this is executed outside of the
// phase runner as it needs mutable access to the service bag (the
// runner borrows the services for the entire phase)
for visitor in visitors {
visitor.finish(VisitorFinishContext {
root: &ctx.root,
services: &mut ctx.services,
});
}
}
for suppression in line_suppressions {
if suppression.did_suppress_signal {
continue;
}
let signal = DiagnosticSignal::new(|| {
SuppressionDiagnostic::new(
category!("suppressions/unused"),
suppression.comment_span,
"Suppression comment is not being used",
)
});
if let ControlFlow::Break(br) = (emit_signal)(&signal) {
return Some(br);
}
}
None
}
}
/// Holds all the state required to run a single analysis phase to completion
struct PhaseRunner<'analyzer, 'phase, L: Language, Matcher, Break, Diag> {
/// Identifier of the phase this runner is executing
phase: Phases,
/// List of visitors being run by this instance of the analyzer for each phase
visitors: &'phase mut [Box<dyn Visitor<Language = L> + 'analyzer>],
/// Holds the metadata for all the rules statically known to the analyzer
metadata: &'analyzer MetadataRegistry,
/// Executor for the query matches emitted by the visitors
query_matcher: &'phase mut Matcher,
/// Queue for pending analyzer signals
signal_queue: BinaryHeap<SignalEntry<'phase, L>>,
/// Language-specific suppression comment parsing function
parse_suppression_comment: SuppressionParser<Diag>,
/// Language-specific suppression comment emitter
apply_suppression_comment: SuppressionCommentEmitter<L>,
/// Line index at the current position of the traversal
line_index: &'phase mut usize,
/// Track active suppression comments per-line, ordered by line index
line_suppressions: &'phase mut Vec<LineSuppression>,
/// Handles analyzer signals emitted by individual rules
emit_signal: &'phase mut SignalHandler<'analyzer, L, Break>,
/// Root node of the file being analyzed
root: &'phase L::Root,
/// Service bag handle for this phase
services: &'phase ServiceBag,
/// Optional text range to restrict the analysis to
range: Option<TextRange>,
/// Analyzer options
options: &'phase AnalyzerOptions,
}
/// Single entry for a suppression comment in the `line_suppressions` buffer
#[derive(Debug)]
struct LineSuppression {
/// Line index this comment is suppressing lint rules for
line_index: usize,
/// Range of source text covered by the suppression comment
comment_span: TextRange,
/// Range of source text this comment is suppressing lint rules for
text_range: TextRange,
/// Set to true if this comment has set the `suppress_all` flag to true
/// (must be restored to false on expiration)
suppress_all: bool,
/// List of all the rules this comment has started suppressing (must be
/// removed from the suppressed set on expiration)
suppressed_rules: Vec<RuleFilter<'static>>,
/// Set to `true` when a signal matching this suppression was emitted and
/// suppressed
did_suppress_signal: bool,
}
impl<'a, 'phase, L, Matcher, Break, Diag> PhaseRunner<'a, 'phase, L, Matcher, Break, Diag>
where
L: Language,
Matcher: QueryMatcher<L>,
Diag: Diagnostic + Clone + Send + Sync + 'static,
{
/// Runs phase 0 over nodes and tokens to process line breaks and
/// suppression comments
fn run_first_phase(mut self) -> ControlFlow<Break> {
let iter = self.root.syntax().preorder_with_tokens(Direction::Next);
for event in iter {
let node_event = match event {
WalkEvent::Enter(SyntaxElement::Node(node)) => WalkEvent::Enter(node),
WalkEvent::Leave(SyntaxElement::Node(node)) => WalkEvent::Leave(node),
// If this is a token enter event, process its text content
WalkEvent::Enter(SyntaxElement::Token(token)) => {
self.handle_token(token)?;
continue;
}
WalkEvent::Leave(SyntaxElement::Token(_)) => {
continue;
}
};
// If this is a node event pass it to the visitors for this phase
for visitor in self.visitors.iter_mut() {
let ctx = VisitorContext {
phase: self.phase,
root: self.root,
services: self.services,
range: self.range,
query_matcher: self.query_matcher,
signal_queue: &mut self.signal_queue,
apply_suppression_comment: self.apply_suppression_comment,
options: self.options,
};
visitor.visit(&node_event, ctx);
}
}
// Flush all remaining pending events
self.flush_matches(None)
}
/// Runs phases 1..N over nodes, since suppression comments were already
/// processed and cached in `run_initial_phase`
fn run_remaining_phases(mut self) -> ControlFlow<Break> {
for event in self.root.syntax().preorder() {
// Run all the active visitors for the phase on the event
for visitor in self.visitors.iter_mut() {
let ctx = VisitorContext {
phase: self.phase,
root: self.root,
services: self.services,
range: self.range,
query_matcher: self.query_matcher,
signal_queue: &mut self.signal_queue,
apply_suppression_comment: self.apply_suppression_comment,
options: self.options,
};
visitor.visit(&event, ctx);
}
// Flush all pending query signals
self.flush_matches(None)?;
}
ControlFlow::Continue(())
}
/// Process the text for a single token, parsing suppression comments and
/// handling line breaks, then flush all pending query signals in the queue
/// whose position is less then the end of the token within the file
fn handle_token(&mut self, token: SyntaxToken<L>) -> ControlFlow<Break> {
// Process the content of the token for comments and newline
for (index, piece) in token.leading_trivia().pieces().enumerate() {
if matches!(
piece.kind(),
TriviaPieceKind::Newline
| TriviaPieceKind::MultiLineComment
| TriviaPieceKind::Skipped
) {
self.bump_line_index(piece.text(), piece.text_range());
}
if let Some(comment) = piece.as_comments() {
self.handle_comment(&token, true, index, comment.text(), piece.text_range())?;
}
}
self.bump_line_index(token.text_trimmed(), token.text_trimmed_range());
for (index, piece) in token.trailing_trivia().pieces().enumerate() {
if matches!(
piece.kind(),
TriviaPieceKind::Newline
| TriviaPieceKind::MultiLineComment
| TriviaPieceKind::Skipped
) {
self.bump_line_index(piece.text(), piece.text_range());
}
if let Some(comment) = piece.as_comments() {
self.handle_comment(&token, false, index, comment.text(), piece.text_range())?;
}
}
// Flush signals from the queue until the end of the current token is reached
let cutoff = token.text_range().end();
self.flush_matches(Some(cutoff))
}
/// Flush all pending query signals in the queue. If `cutoff` is specified,
/// signals that start after this position in the file will be skipped
fn flush_matches(&mut self, cutoff: Option<TextSize>) -> ControlFlow<Break> {
while let Some(entry) = self.signal_queue.peek() {
let start = entry.text_range.start();
if let Some(cutoff) = cutoff {
if start >= cutoff {
break;
}
}
// Search for an active suppression comment covering the range of
// this signal: first try to load the last line suppression and see
// if it matches the current line index, otherwise perform a binary
// search over all the previously seen suppressions to find one
// with a matching range
let suppression = self.line_suppressions.last_mut().filter(|suppression| {
suppression.line_index == *self.line_index
&& suppression.text_range.start() <= start
});
let suppression = match suppression {
Some(suppression) => Some(suppression),
None => {
let index = self.line_suppressions.binary_search_by(|suppression| {
if suppression.text_range.end() < entry.text_range.start() {
Ordering::Less
} else if entry.text_range.end() < suppression.text_range.start() {
Ordering::Greater
} else {
Ordering::Equal
}
});
index.ok().map(|index| &mut self.line_suppressions[index])
}
};
let suppression = suppression.filter(|suppression| {
if suppression.suppress_all {
return true;
}
suppression
.suppressed_rules
.iter()
.any(|filter| *filter == entry.rule)
});
// If the signal is being suppressed mark the line suppression as
// hit, otherwise emit the signal
if let Some(suppression) = suppression {
suppression.did_suppress_signal = true;
} else if range_match(self.range, entry.text_range) {
(self.emit_signal)(&*entry.signal)?;
}
// SAFETY: This removes `query` from the queue, it is known to
// exist since the `while let Some` block was entered
self.signal_queue.pop().unwrap();
}
ControlFlow::Continue(())
}
/// Parse the text content of a comment trivia piece for suppression
/// comments, and create line suppression entries accordingly
fn handle_comment(
&mut self,
token: &SyntaxToken<L>,
is_leading: bool,
index: usize,
text: &str,
range: TextRange,
) -> ControlFlow<Break> {
let mut suppress_all = false;
let mut suppressions = Vec::new();
let mut has_legacy = false;
for result in (self.parse_suppression_comment)(text) {
let kind = match result {
Ok(kind) => kind,
Err(diag) => {
// Emit the suppression parser diagnostic
let signal = DiagnosticSignal::new(move || {
let location = diag.location();
let span = location.span.map_or(range, |span| span + range.start());
diag.clone().with_file_span(span)
});
(self.emit_signal)(&signal)?;
continue;
}
};
let rule = match kind {
SuppressionKind::Everything => None,
SuppressionKind::Rule(rule) => Some(rule),
SuppressionKind::MaybeLegacy(rule) => Some(rule),
};
if let Some(rule) = rule {
let group_rule = rule.find('/').map(|index| {
let (start, end) = rule.split_at(index);
(start, &end[1..])
});
let key = match group_rule {
None => self.metadata.find_group(rule).map(RuleFilter::from),
Some((group, rule)) => {
self.metadata.find_rule(group, rule).map(RuleFilter::from)
}
};
if let Some(key) = key {
suppressions.push(key);
has_legacy |= matches!(kind, SuppressionKind::MaybeLegacy(_));
} else if range_match(self.range, range) {
// Emit a warning for the unknown rule
let signal = DiagnosticSignal::new(move || match group_rule {
Some((group, rule)) => SuppressionDiagnostic::new(
category!("suppressions/unknownRule"),
range,
format_args!("Unknown lint rule {group}/{rule} in suppression comment"),
),
None => SuppressionDiagnostic::new(
category!("suppressions/unknownGroup"),
range,
format_args!("Unknown lint rule group {rule} in suppression comment"),
),
});
(self.emit_signal)(&signal)?;
}
} else {
suppressions.clear();
suppress_all = true;
// If this if a "suppress all lints" comment, no need to
// parse anything else
break;
}
}
// Emit a warning for legacy suppression syntax
if has_legacy && range_match(self.range, range) {
let signal = DiagnosticSignal::new(move || {
SuppressionDiagnostic::new(
category!("suppressions/deprecatedSyntax"),
range,
"Suppression is using a deprecated syntax",
)
.with_tags(DiagnosticTags::DEPRECATED_CODE)
});
let signal = signal
.with_action(|| update_suppression(self.root, token, is_leading, index, text));
(self.emit_signal)(&signal)?;
}
if !suppress_all && suppressions.is_empty() {
return ControlFlow::Continue(());
}
// Suppression comments apply to the next line
let line_index = *self.line_index + 1;
// If the last suppression was on the same or previous line, extend its
// range and set of supressed rules with the content for the new suppression
if let Some(last_suppression) = self.line_suppressions.last_mut() {
if last_suppression.line_index == line_index
|| last_suppression.line_index + 1 == line_index
{
last_suppression.line_index = line_index;
last_suppression.text_range = last_suppression.text_range.cover(range);
last_suppression.suppress_all |= suppress_all;
if !last_suppression.suppress_all {
last_suppression.suppressed_rules.extend(suppressions);
} else {
last_suppression.suppressed_rules.clear();
}
return ControlFlow::Continue(());
}
}
let entry = LineSuppression {
line_index,
comment_span: range,
text_range: range,
suppress_all,
suppressed_rules: suppressions,
did_suppress_signal: false,
};
self.line_suppressions.push(entry);
ControlFlow::Continue(())
}
/// Check a piece of source text (token or trivia) for line breaks and
/// increment the line index accordingly, extending the range of the
/// current suppression as required
fn bump_line_index(&mut self, text: &str, range: TextRange) {
let mut did_match = false;
for (index, _) in text.match_indices('\n') {
if let Some(last_suppression) = self.line_suppressions.last_mut() {
if last_suppression.line_index == *self.line_index {
let index = TextSize::try_from(index).expect(
"integer overflow while converting a suppression line to `TextSize`",
);
let range = TextRange::at(range.start(), index);
last_suppression.text_range = last_suppression.text_range.cover(range);
did_match = true;
}
}
*self.line_index += 1;
}
if !did_match {
if let Some(last_suppression) = self.line_suppressions.last_mut() {
if last_suppression.line_index == *self.line_index {
last_suppression.text_range = last_suppression.text_range.cover(range);
}
}
}
}
}
fn range_match(filter: Option<TextRange>, range: TextRange) -> bool {
filter.map_or(true, |filter| filter.intersect(range).is_some())
}
/// Signature for a suppression comment parser function
///
/// This function receives the text content of a comment and returns a list of
/// lint suppressions as an optional lint rule (if the lint rule is `None` the
/// comment is interpreted as suppressing all lints)
///
/// # Examples
///
/// - `// rome-ignore format` -> `vec![]`
/// - `// rome-ignore lint` -> `vec![Everything]`
/// - `// rome-ignore lint/style/useWhile` -> `vec![Rule("style/useWhile")]`
/// - `// rome-ignore lint/style/useWhile lint/nursery/noUnreachable` -> `vec![Rule("style/useWhile"), Rule("nursery/noUnreachable")]`
/// - `// rome-ignore lint(style/useWhile)` -> `vec![MaybeLegacy("style/useWhile")]`
/// - `// rome-ignore lint(style/useWhile) lint(nursery/noUnreachable)` -> `vec![MaybeLegacy("style/useWhile"), MaybeLegacy("nursery/noUnreachable")]`
type SuppressionParser<D> = fn(&str) -> Vec<Result<SuppressionKind, D>>;
/// This enum is used to categorize what is disabled by a suppression comment and with what syntax
pub enum SuppressionKind<'a> {
/// A suppression disabling all lints eg. `// rome-ignore lint`
Everything,
/// A suppression disabling a specific rule eg. `// rome-ignore lint/style/useWhile`
Rule(&'a str),
/// A suppression using the legacy syntax to disable a specific rule eg. `// rome-ignore lint(style/useWhile)`
MaybeLegacy(&'a str),
}
fn update_suppression<L: Language>(
root: &L::Root,
token: &SyntaxToken<L>,
is_leading: bool,
index: usize,
text: &str,
) -> Option<AnalyzerAction<L>> {
let old_token = token.clone();
let new_token = token.clone().detach();
let old_trivia = if is_leading {
old_token.leading_trivia()
} else {
old_token.trailing_trivia()
};
let old_trivia: Vec<_> = old_trivia.pieces().collect();
let mut text = text.to_string();
while let Some(range_start) = text.find("lint(") {
let range_end = range_start + text[range_start..].find(')')?;
text.replace_range(range_end..range_end + 1, "");
text.replace_range(range_start + 4..range_start + 5, "/");
}
let new_trivia = old_trivia.iter().enumerate().map(|(piece_index, piece)| {
if piece_index == index {
(piece.kind(), text.as_str())
} else {
(piece.kind(), piece.text())
}
});
let new_token = if is_leading {
new_token.with_leading_trivia(new_trivia)
} else {
new_token.with_trailing_trivia(new_trivia)
};
let mut mutation = BatchMutation::new(root.syntax().clone());
mutation.replace_token_discard_trivia(old_token, new_token);
Some(AnalyzerAction {
rule_name: None,
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! {
"Rewrite suppression to use the newer syntax"
}
.to_owned(),
mutation,
})
}
/// Payload received by the function responsible to mark a suppression comment
pub struct SuppressionCommentEmitterPayload<'a, L: Language> {
/// The possible offset found in the [TextRange] of the emitted diagnostic
pub token_offset: TokenAtOffset<SyntaxToken<L>>,
/// A [BatchMutation] where the consumer can apply the suppression comment
pub mutation: &'a mut BatchMutation<L>,
/// A string equals to "rome-ignore: lint(<RULE_GROUP>/<RULE_NAME>)"
pub suppression_text: &'a str,
/// The original range of the diagnostic where the rule was triggered
pub diagnostic_text_range: &'a TextRange,
}
/// Convenient type that to mark a function that is responsible to create a mutation to add a suppression comment.
type SuppressionCommentEmitter<L> = fn(SuppressionCommentEmitterPayload<L>);
type SignalHandler<'a, L, Break> = &'a mut dyn FnMut(&dyn AnalyzerSignal<L>) -> ControlFlow<Break>;
/// Allow filtering a single rule or group of rules by their names
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub enum RuleFilter<'a> {
Group(&'a str),
Rule(&'a str, &'a str),
}
impl RuleFilter<'_> {
/// Return `true` if the group `G` matches this filter
fn match_group<G: RuleGroup>(self) -> bool {
match self {
RuleFilter::Group(group) => group == G::NAME,
RuleFilter::Rule(group, _) => group == G::NAME,
}
}
/// Return `true` if the rule `R` matches this filter
fn match_rule<R>(self) -> bool
where
R: Rule,
{
match self {
RuleFilter::Group(group) => group == <R::Group as RuleGroup>::NAME,
RuleFilter::Rule(group, rule) => {
group == <R::Group as RuleGroup>::NAME && rule == R::METADATA.name
}
}
}
}
impl<'a> Debug for RuleFilter<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Display::fmt(self, f)
}
}
impl<'a> Display for RuleFilter<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
RuleFilter::Group(group) => {
write!(f, "{group}")
}
RuleFilter::Rule(group, rule) => {
write!(f, "{group}/{rule}")
}
}
}
}
/// Allows filtering the list of rules that will be executed in a run of the analyzer,
/// and at what source code range signals (diagnostics or actions) may be raised
#[derive(Debug, Default, Clone, Copy)]
pub struct AnalysisFilter<'a> {
/// Only allow rules with these categories to emit signals
pub categories: RuleCategories,
/// Only allow rules matching these names to emit signals
pub enabled_rules: Option<&'a [RuleFilter<'a>]>,
/// Do not allow rules matching these names to emit signals
pub disabled_rules: Option<&'a [RuleFilter<'a>]>,
/// Only emit signals matching this text range
pub range: Option<TextRange>,
}
impl<'analysis> AnalysisFilter<'analysis> {
/// Return `true` if the category `C` matches this filter
pub fn match_category<C: GroupCategory>(&self) -> bool {
self.categories.contains(C::CATEGORY.into())
}
/// Return `true` if the group `G` matches this filter
pub fn match_group<G: RuleGroup>(&self) -> bool {
self.match_category::<G::Category>()
&& self.enabled_rules.map_or(true, |enabled_rules| {
enabled_rules.iter().any(|filter| filter.match_group::<G>())
})
&& self.disabled_rules.map_or(true, |disabled_rules| {
!disabled_rules
.iter()
.any(|filter| filter.match_group::<G>())
})
}
/// Return `true` if the rule `R` matches this filter
pub fn match_rule<R>(&self) -> bool
where
R: Rule,
{
self.match_group::<R::Group>()
&& self.enabled_rules.map_or(true, |enabled_rules| {
enabled_rules.iter().any(|filter| filter.match_rule::<R>())
})
&& self.disabled_rules.map_or(true, |disabled_rules| {
!disabled_rules.iter().any(|filter| filter.match_rule::<R>())
})
}
/// It creates a new filter with the set of [enabled rules](RuleFilter) passed as argument
pub fn from_enabled_rules(enabled_rules: Option<&'analysis [RuleFilter<'analysis>]>) -> Self {
Self {
enabled_rules,
..AnalysisFilter::default()
}
}
}
/// Utility type to be used as a default value for the `B` generic type on
/// `analyze` when the provided callback never breaks
///
/// This should eventually get replaced with the `!` type when it gets stabilized
pub enum Never {}
/// Type alias of [ops::ControlFlow] with the `B` generic type defaulting to [Never]
///
/// By default the analysis loop never breaks, so it behaves mostly like
/// `let b = loop {};` and has a "break type" of `!` (the `!` type isn't stable
/// yet so I'm using an empty enum instead but they're identical for this
/// purpose)
///
/// In practice it's not really a `loop` but a `for` because it's iterating on
/// all nodes in the syntax tree, so when it reaches the end of the iterator
/// the loop will exit but without producing a value of type `B`: for this
/// reason the `analyze` function returns an `Option<B>` that's set to
/// `Some(B)` if the callback did break, and `None` if the analysis reached the
/// end of the file.
///
/// Most consumers of the analyzer will want to analyze the entire file at once
/// and never break, so using [Never] as the type of `B` in this case lets the
/// compiler know the `ControlFlow::Break` branch will never be taken and can
/// be optimized out, as well as completely remove the `return Some` case
/// (`Option<Never>` has a size of 0 and can be elided, while `Option<()>` has
/// a size of 1 as it still need to store a discriminant)
pub type ControlFlow<B = Never> = ops::ControlFlow<B>;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/categories.rs | crates/rome_analyze/src/categories.rs | use std::borrow::Cow;
use bitflags::bitflags;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
pub enum RuleCategory {
/// This rule checks the syntax according to the language specification
/// and emits error diagnostics accordingly
Syntax,
/// This rule performs static analysis of the source code to detect
/// invalid or error-prone patterns, and emits diagnostics along with
/// proposed fixes
Lint,
/// This rule detects refactoring opportunities and emits code action
/// signals
Action,
/// This rule detects transformations that should be applied to the code
Transformation,
}
/// Actions that suppress rules should start with this string
pub const SUPPRESSION_ACTION_CATEGORY: &str = "quickfix.suppressRule";
/// The category of a code action, this type maps directly to the
/// [CodeActionKind] type in the Language Server Protocol specification
///
/// [CodeActionKind]: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#codeActionKind
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
pub enum ActionCategory {
/// Base kind for quickfix actions: 'quickfix'.
///
/// This action provides a fix to the diagnostic emitted by the same signal
QuickFix,
/// Base kind for refactoring actions: 'refactor'.
///
/// This action provides an optional refactor opportunity
Refactor(RefactorKind),
/// Base kind for source actions: `source`.
///
/// Source code actions apply to the entire file.
Source(SourceActionKind),
/// This action is using a base kind not covered by any of the previous
/// variants
Other(Cow<'static, str>),
}
impl ActionCategory {
/// Returns true if this category matches the provided filter
///
/// ## Examples
///
/// ```
/// use rome_analyze::{ActionCategory, RefactorKind};
///
/// assert!(ActionCategory::QuickFix.matches("quickfix"));
/// assert!(!ActionCategory::QuickFix.matches("refactor"));
///
/// assert!(ActionCategory::Refactor(RefactorKind::None).matches("refactor"));
/// assert!(!ActionCategory::Refactor(RefactorKind::None).matches("refactor.extract"));
///
/// assert!(ActionCategory::Refactor(RefactorKind::Extract).matches("refactor"));
/// assert!(ActionCategory::Refactor(RefactorKind::Extract).matches("refactor.extract"));
/// ```
pub fn matches(&self, filter: &str) -> bool {
self.to_str().starts_with(filter)
}
/// Returns the representation of this [ActionCategory] as a `CodeActionKind` string
pub fn to_str(&self) -> Cow<'static, str> {
match self {
ActionCategory::QuickFix => Cow::Borrowed("quickfix.rome"),
ActionCategory::Refactor(RefactorKind::None) => Cow::Borrowed("refactor.rome"),
ActionCategory::Refactor(RefactorKind::Extract) => {
Cow::Borrowed("refactor.extract.rome")
}
ActionCategory::Refactor(RefactorKind::Inline) => Cow::Borrowed("refactor.inline.rome"),
ActionCategory::Refactor(RefactorKind::Rewrite) => {
Cow::Borrowed("refactor.rewrite.rome")
}
ActionCategory::Refactor(RefactorKind::Other(tag)) => {
Cow::Owned(format!("refactor.{tag}.rome"))
}
ActionCategory::Source(SourceActionKind::None) => Cow::Borrowed("source.rome"),
ActionCategory::Source(SourceActionKind::FixAll) => Cow::Borrowed("source.fixAll.rome"),
ActionCategory::Source(SourceActionKind::OrganizeImports) => {
Cow::Borrowed("source.organizeImports.rome")
}
ActionCategory::Source(SourceActionKind::Other(tag)) => {
Cow::Owned(format!("source.{tag}.rome"))
}
ActionCategory::Other(tag) => Cow::Owned(format!("{tag}.rome")),
}
}
}
/// The sub-category of a refactor code action
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
pub enum RefactorKind {
/// This action describes a refactor with no particular sub-category
None,
/// Base kind for refactoring extraction actions: 'refactor.extract'.
///
/// Example extract actions:
/// - Extract method
/// - Extract function
/// - Extract variable
/// - Extract interface from class
Extract,
/// Base kind for refactoring inline actions: 'refactor.inline'.
///
/// Example inline actions:
/// - Inline function
/// - Inline variable
/// - Inline constant
/// - ...
Inline,
/// Base kind for refactoring rewrite actions: 'refactor.rewrite'.
///
/// Example rewrite actions:
/// - Convert JavaScript function to class
/// - Add or remove parameter
/// - Encapsulate field
/// - Make method static
/// - Move method to base class
/// - ...
Rewrite,
/// This action is using a refactor kind not covered by any of the previous
/// variants
Other(Cow<'static, str>),
}
/// The sub-category of a source code action
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
pub enum SourceActionKind {
/// This action describes a source action with no particular sub-category
None,
// Base kind for a 'fix all' source action: `source.fixAll`.
//
// 'Fix all' actions automatically fix errors that have a clear fix that
// do not require user input. They should not suppress errors or perform
// unsafe fixes such as generating new types or classes.
FixAll,
/// Base kind for an organize imports source action: `source.organizeImports`.
OrganizeImports,
/// This action is using a source action kind not covered by any of the
/// previous variants
Other(Cow<'static, str>),
}
bitflags! {
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct RuleCategories: u8 {
const SYNTAX = 1 << RuleCategory::Syntax as u8;
const LINT = 1 << RuleCategory::Lint as u8;
const ACTION = 1 << RuleCategory::Action as u8;
const TRANSFORMATION = 1 << RuleCategory::Transformation as u8;
}
}
impl Default for RuleCategories {
fn default() -> Self {
Self::all()
}
}
impl RuleCategories {
pub fn is_syntax(&self) -> bool {
*self == RuleCategories::SYNTAX
}
}
impl From<RuleCategory> for RuleCategories {
fn from(input: RuleCategory) -> Self {
match input {
RuleCategory::Syntax => RuleCategories::SYNTAX,
RuleCategory::Lint => RuleCategories::LINT,
RuleCategory::Action => RuleCategories::ACTION,
RuleCategory::Transformation => RuleCategories::TRANSFORMATION,
}
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for RuleCategories {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut flags = Vec::new();
if self.contains(Self::SYNTAX) {
flags.push(RuleCategory::Syntax);
}
if self.contains(Self::LINT) {
flags.push(RuleCategory::Lint);
}
if self.contains(Self::ACTION) {
flags.push(RuleCategory::Action);
}
if self.contains(Self::TRANSFORMATION) {
flags.push(RuleCategory::Transformation);
}
serializer.collect_seq(flags)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for RuleCategories {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::{self, SeqAccess};
use std::fmt::{self, Formatter};
struct Visitor;
impl<'de> de::Visitor<'de> for Visitor {
type Value = RuleCategories;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
write!(formatter, "RuleCategories")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut result = RuleCategories::empty();
while let Some(item) = seq.next_element::<RuleCategory>()? {
result |= RuleCategories::from(item);
}
Ok(result)
}
}
deserializer.deserialize_seq(Visitor)
}
}
#[cfg(feature = "serde")]
impl schemars::JsonSchema for RuleCategories {
fn schema_name() -> String {
String::from("RuleCategories")
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
<Vec<RuleCategory>>::json_schema(gen)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/syntax.rs | crates/rome_analyze/src/syntax.rs | use rome_rowan::{AstNode, Language, SyntaxNode, WalkEvent};
use crate::{
registry::NodeLanguage, AddVisitor, Phases, QueryKey, QueryMatch, Queryable, ServiceBag,
Visitor, VisitorContext,
};
/// Query type usable by lint rules to match on specific [AstNode] types
#[derive(Clone)]
pub struct Ast<N>(pub N);
impl<N> Queryable for Ast<N>
where
N: AstNode + 'static,
{
type Input = SyntaxNode<NodeLanguage<N>>;
type Output = N;
type Language = NodeLanguage<N>;
type Services = ();
fn build_visitor(
analyzer: &mut impl AddVisitor<Self::Language>,
_: &<Self::Language as Language>::Root,
) {
analyzer.add_visitor(Phases::Syntax, SyntaxVisitor::default);
}
fn key() -> QueryKey<Self::Language> {
QueryKey::Syntax(N::KIND_SET)
}
fn unwrap_match(_: &ServiceBag, node: &Self::Input) -> Self::Output {
N::unwrap_cast(node.clone())
}
}
impl<L: Language + 'static> QueryMatch for SyntaxNode<L> {
fn text_range(&self) -> rome_rowan::TextRange {
self.text_trimmed_range()
}
}
/// The [SyntaxVisitor] is the simplest form of visitor implemented for the
/// analyzer, it simply broadcast each [WalkEvent::Enter] as a query match
/// event for the [SyntaxNode] being entered
pub struct SyntaxVisitor<L: Language> {
/// If a subtree is currently being skipped by the visitor, for instance
/// because it has a suppression comment, this stores the root [SyntaxNode]
/// of that subtree. The visitor will then ignore all events until it
/// receives a [WalkEvent::Leave] for the `skip_subtree` node
skip_subtree: Option<SyntaxNode<L>>,
}
impl<L: Language> Default for SyntaxVisitor<L> {
fn default() -> Self {
Self { skip_subtree: None }
}
}
impl<L: Language + 'static> Visitor for SyntaxVisitor<L> {
type Language = L;
fn visit(&mut self, event: &WalkEvent<SyntaxNode<Self::Language>>, mut ctx: VisitorContext<L>) {
let node = match event {
WalkEvent::Enter(node) => node,
WalkEvent::Leave(node) => {
if let Some(skip_subtree) = &self.skip_subtree {
if skip_subtree == node {
self.skip_subtree = None;
}
}
return;
}
};
if self.skip_subtree.is_some() {
return;
}
if let Some(range) = ctx.range {
if node.text_range().ordering(range).is_ne() {
self.skip_subtree = Some(node.clone());
return;
}
}
ctx.match_query(node.clone());
}
}
#[cfg(test)]
mod tests {
use rome_rowan::{
raw_language::{RawLanguage, RawLanguageKind, RawLanguageRoot, RawSyntaxTreeBuilder},
AstNode, SyntaxNode,
};
use std::convert::Infallible;
use crate::{
matcher::MatchQueryParams, registry::Phases, Analyzer, AnalyzerContext, AnalyzerOptions,
AnalyzerSignal, ControlFlow, MetadataRegistry, Never, QueryMatcher, ServiceBag,
SyntaxVisitor,
};
#[derive(Default)]
struct BufferMatcher {
nodes: Vec<RawLanguageKind>,
}
impl<'a> QueryMatcher<RawLanguage> for &'a mut BufferMatcher {
fn match_query(&mut self, params: MatchQueryParams<RawLanguage>) {
self.nodes.push(
params
.query
.downcast::<SyntaxNode<RawLanguage>>()
.unwrap()
.kind(),
);
}
}
/// Checks the syntax visitor emits a [QueryMatch] for each node in the syntax tree
#[test]
fn syntax_visitor() {
let root = {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::ROOT);
builder.start_node(RawLanguageKind::EXPRESSION_LIST);
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::NUMBER_TOKEN, "1");
builder.finish_node();
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::NUMBER_TOKEN, "2");
builder.finish_node();
builder.finish_node();
builder.finish_node();
RawLanguageRoot::unwrap_cast(builder.finish())
};
let mut matcher = BufferMatcher::default();
let mut emit_signal =
|_: &dyn AnalyzerSignal<RawLanguage>| -> ControlFlow<Never> { unreachable!() };
let metadata = MetadataRegistry::default();
let mut analyzer = Analyzer::new(
&metadata,
&mut matcher,
|_| -> Vec<Result<_, Infallible>> { unreachable!() },
|_| unreachable!(),
&mut emit_signal,
);
analyzer.add_visitor(Phases::Syntax, Box::<SyntaxVisitor<RawLanguage>>::default());
let ctx: AnalyzerContext<RawLanguage> = AnalyzerContext {
root,
range: None,
services: ServiceBag::default(),
options: &AnalyzerOptions::default(),
};
let result: Option<Never> = analyzer.run(ctx);
assert!(result.is_none());
assert_eq!(
matcher.nodes.as_slice(),
&[
RawLanguageKind::ROOT,
RawLanguageKind::EXPRESSION_LIST,
RawLanguageKind::LITERAL_EXPRESSION,
RawLanguageKind::LITERAL_EXPRESSION
]
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/registry.rs | crates/rome_analyze/src/registry.rs | use crate::{
context::RuleContext,
matcher::{GroupKey, MatchQueryParams},
query::{QueryKey, Queryable},
signals::RuleSignal,
AddVisitor, AnalysisFilter, GroupCategory, QueryMatcher, Rule, RuleGroup, RuleKey,
RuleMetadata, ServiceBag, SignalEntry, Visitor,
};
use rome_diagnostics::Error;
use rome_rowan::{AstNode, Language, RawSyntaxKind, SyntaxKind, SyntaxNode};
use rustc_hash::{FxHashMap, FxHashSet};
use std::{
any::TypeId,
borrow,
collections::{BTreeMap, BTreeSet},
};
/// Defines all the phases that the [RuleRegistry] supports.
#[repr(usize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Phases {
Syntax = 0,
Semantic = 1,
}
/// Defines which phase a rule will run. This will be defined
/// by the set of services a rule demands.
pub trait Phase {
fn phase() -> Phases;
}
/// If a rule do not need any service it can run on the syntax phase.
impl Phase for () {
fn phase() -> Phases {
Phases::Syntax
}
}
pub trait RegistryVisitor<L: Language> {
/// Record the category `C` to this visitor
fn record_category<C: GroupCategory<Language = L>>(&mut self) {
C::record_groups(self);
}
/// Record the group `G` to this visitor
fn record_group<G: RuleGroup<Language = L>>(&mut self) {
G::record_rules(self);
}
/// Record the rule `R` to this visitor
fn record_rule<R>(&mut self)
where
R: Rule + 'static,
R::Query: Queryable<Language = L>,
<R::Query as Queryable>::Output: Clone;
}
/// Stores metadata information for all the rules in the registry, sorted
/// alphabetically
#[derive(Debug, Default)]
pub struct MetadataRegistry {
inner: BTreeSet<MetadataKey>,
}
impl MetadataRegistry {
/// Return a unique identifier for a rule group if it's known by this registry
pub fn find_group(&self, group: &str) -> Option<GroupKey> {
let key = self.inner.get(group)?;
Some(key.into_group_key())
}
/// Return a unique identifier for a rule if it's known by this registry
pub fn find_rule(&self, group: &str, rule: &str) -> Option<RuleKey> {
let key = self.inner.get(&(group, rule))?;
Some(key.into_rule_key())
}
pub(crate) fn insert_rule(&mut self, group: &'static str, rule: &'static str) {
self.inner.insert(MetadataKey {
inner: (group, rule),
});
}
}
impl<L: Language> RegistryVisitor<L> for MetadataRegistry {
fn record_rule<R>(&mut self)
where
R: Rule + 'static,
R::Query: Queryable<Language = L>,
<R::Query as Queryable>::Output: Clone,
{
self.insert_rule(<R::Group as RuleGroup>::NAME, R::METADATA.name);
}
}
/// The rule registry holds type-erased instances of all active analysis rules
/// for each phase.
/// What defines a phase is the set of services that a phase offers. Currently
/// we have:
/// - Syntax Phase: No services are offered, thus its rules can be run immediately;
/// - Semantic Phase: Offers the semantic model, thus these rules can only run
/// after the "SemanticModel" is ready, which demands a whole transverse of the parsed tree.
pub struct RuleRegistry<L: Language> {
/// Holds a collection of rules for each phase.
phase_rules: [PhaseRules<L>; 2],
}
impl<L: Language + Default> RuleRegistry<L> {
pub fn builder<'a>(
filter: &'a AnalysisFilter<'a>,
root: &'a L::Root,
) -> RuleRegistryBuilder<'a, L> {
RuleRegistryBuilder {
filter,
root,
registry: RuleRegistry {
phase_rules: Default::default(),
},
visitors: BTreeMap::default(),
services: ServiceBag::default(),
diagnostics: Vec::new(),
}
}
}
/// Holds a collection of rules for each phase.
#[derive(Default)]
struct PhaseRules<L: Language> {
/// Maps the [TypeId] of known query matches types to the corresponding list of rules
type_rules: FxHashMap<TypeId, TypeRules<L>>,
/// Holds a list of states for all the rules in this phase
rule_states: Vec<RuleState<L>>,
}
enum TypeRules<L: Language> {
SyntaxRules { rules: Vec<SyntaxKindRules<L>> },
TypeRules { rules: Vec<RegistryRule<L>> },
}
pub struct RuleRegistryBuilder<'a, L: Language> {
filter: &'a AnalysisFilter<'a>,
root: &'a L::Root,
// Rule Registry
registry: RuleRegistry<L>,
// Analyzer Visitors
visitors: BTreeMap<(Phases, TypeId), Box<dyn Visitor<Language = L>>>,
// Service Bag
services: ServiceBag,
diagnostics: Vec<Error>,
}
impl<L: Language + Default + 'static> RegistryVisitor<L> for RuleRegistryBuilder<'_, L> {
fn record_category<C: GroupCategory<Language = L>>(&mut self) {
if self.filter.match_category::<C>() {
C::record_groups(self);
}
}
fn record_group<G: RuleGroup<Language = L>>(&mut self) {
if self.filter.match_group::<G>() {
G::record_rules(self);
}
}
/// Add the rule `R` to the list of rules stores in this registry instance
fn record_rule<R>(&mut self)
where
R: Rule + 'static,
<R as Rule>::Options: Default,
R::Query: Queryable<Language = L>,
<R::Query as Queryable>::Output: Clone,
{
if !self.filter.match_rule::<R>() {
return;
}
let phase = R::phase() as usize;
let phase = &mut self.registry.phase_rules[phase];
let rule = RegistryRule::new::<R>(phase.rule_states.len());
match <R::Query as Queryable>::key() {
QueryKey::Syntax(key) => {
let TypeRules::SyntaxRules { rules } = phase
.type_rules
.entry(TypeId::of::<SyntaxNode<L>>())
.or_insert_with(|| TypeRules::SyntaxRules { rules: Vec::new() })
else { unreachable!("the SyntaxNode type has already been registered as a TypeRules instead of a SyntaxRules, this is generally caused by an implementation of `Queryable::key` returning a `QueryKey::TypeId` with the type ID of `SyntaxNode`") };
// Iterate on all the SyntaxKind variants this node can match
for kind in key.iter() {
// Convert the numerical value of `kind` to an index in the
// `nodes` vector
let RawSyntaxKind(index) = kind.to_raw();
let index = usize::from(index);
// Ensure the vector has enough capacity by inserting empty
// `SyntaxKindRules` as required
if rules.len() <= index {
rules.resize_with(index + 1, SyntaxKindRules::new);
}
// Insert a handle to the rule `R` into the `SyntaxKindRules` entry
// corresponding to the SyntaxKind index
let node = &mut rules[index];
node.rules.push(rule);
}
}
QueryKey::TypeId(key) => {
let TypeRules::TypeRules { rules } = phase
.type_rules
.entry(key)
.or_insert_with(|| TypeRules::TypeRules { rules: Vec::new() })
else { unreachable!("the query type has already been registered as a SyntaxRules instead of a TypeRules, this is generally ca used by an implementation of `Queryable::key` returning a `QueryKey::TypeId` with the type ID of `SyntaxNode`") };
rules.push(rule);
}
}
phase.rule_states.push(RuleState::default());
<R::Query as Queryable>::build_visitor(&mut self.visitors, self.root);
}
}
impl<L: Language> AddVisitor<L> for BTreeMap<(Phases, TypeId), Box<dyn Visitor<Language = L>>> {
fn add_visitor<F, V>(&mut self, phase: Phases, visitor: F)
where
F: FnOnce() -> V,
V: Visitor<Language = L> + 'static,
{
self.entry((phase, TypeId::of::<V>()))
.or_insert_with(move || Box::new((visitor)()));
}
}
type BuilderResult<L> = (
RuleRegistry<L>,
ServiceBag,
Vec<Error>,
BTreeMap<(Phases, TypeId), Box<dyn Visitor<Language = L>>>,
);
impl<L: Language> RuleRegistryBuilder<'_, L> {
pub fn build(self) -> BuilderResult<L> {
(
self.registry,
self.services,
self.diagnostics,
self.visitors,
)
}
}
impl<L: Language + 'static> QueryMatcher<L> for RuleRegistry<L> {
fn match_query(&mut self, mut params: MatchQueryParams<L>) {
let phase = &mut self.phase_rules[params.phase as usize];
let query_type = params.query.type_id();
let Some(rules) = phase.type_rules.get(&query_type) else { return };
let rules = match rules {
TypeRules::SyntaxRules { rules } => {
let node = params.query.downcast_ref::<SyntaxNode<L>>().unwrap();
// Convert the numerical value of the SyntaxKind to an index in the
// `syntax` vector
let RawSyntaxKind(kind) = node.kind().to_raw();
let kind = usize::from(kind);
// Lookup the syntax entry corresponding to the SyntaxKind index
match rules.get(kind) {
Some(entry) => &entry.rules,
None => return,
}
}
TypeRules::TypeRules { rules } => rules,
};
// Run all the rules registered to this QueryMatch
for rule in rules {
let state = &mut phase.rule_states[rule.state_index];
// TODO: #3394 track error in the signal queue
let _ = (rule.run)(&mut params, state);
}
}
}
/// [SyntaxKindRules] holds a collection of [Rule]s that match a specific [SyntaxKind] value
struct SyntaxKindRules<L: Language> {
rules: Vec<RegistryRule<L>>,
}
impl<L: Language> SyntaxKindRules<L> {
fn new() -> Self {
Self { rules: Vec::new() }
}
}
pub(crate) type RuleLanguage<R> = QueryLanguage<<R as Rule>::Query>;
pub(crate) type QueryLanguage<N> = <N as Queryable>::Language;
pub(crate) type NodeLanguage<N> = <N as AstNode>::Language;
pub(crate) type RuleRoot<R> = LanguageRoot<RuleLanguage<R>>;
pub type LanguageRoot<L> = <L as Language>::Root;
/// Key struct for a rule in the metadata map, sorted alphabetically
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct MetadataKey {
inner: (&'static str, &'static str),
}
impl MetadataKey {
fn into_group_key(self) -> GroupKey {
let (group, _) = self.inner;
GroupKey::new(group)
}
fn into_rule_key(self) -> RuleKey {
let (group, rule) = self.inner;
RuleKey::new(group, rule)
}
}
impl<'a> borrow::Borrow<(&'a str, &'a str)> for MetadataKey {
fn borrow(&self) -> &(&'a str, &'a str) {
&self.inner
}
}
impl borrow::Borrow<str> for MetadataKey {
fn borrow(&self) -> &str {
self.inner.0
}
}
/// Metadata entry for a rule and its group in the registry
pub struct RegistryRuleMetadata {
pub group: &'static str,
pub rule: RuleMetadata,
}
impl RegistryRuleMetadata {
pub fn to_rule_key(&self) -> RuleKey {
RuleKey::new(self.group, self.rule.name)
}
}
/// Internal representation of a single rule in the registry
#[derive(Copy, Clone)]
pub struct RegistryRule<L: Language> {
run: RuleExecutor<L>,
state_index: usize,
}
/// Internal state for a given rule
#[derive(Default)]
struct RuleState<L: Language> {
suppressions: RuleSuppressions<L>,
}
/// Set of nodes this rule has suppressed from matching its query
#[derive(Default)]
pub struct RuleSuppressions<L: Language> {
inner: FxHashSet<SyntaxNode<L>>,
}
impl<L: Language> RuleSuppressions<L> {
/// Suppress query matching for the given node
pub fn suppress_node(&mut self, node: SyntaxNode<L>) {
self.inner.insert(node);
}
}
/// Executor for rule as a generic function pointer
type RuleExecutor<L> = fn(&mut MatchQueryParams<L>, &mut RuleState<L>) -> Result<(), Error>;
impl<L: Language + Default> RegistryRule<L> {
fn new<R>(state_index: usize) -> Self
where
R: Rule + 'static,
<R as Rule>::Options: Default,
R::Query: Queryable<Language = L> + 'static,
<R::Query as Queryable>::Output: Clone,
{
/// Generic implementation of RuleExecutor for any rule type R
fn run<R>(
params: &mut MatchQueryParams<RuleLanguage<R>>,
state: &mut RuleState<RuleLanguage<R>>,
) -> Result<(), Error>
where
R: Rule + 'static,
R::Query: 'static,
<R::Query as Queryable>::Output: Clone,
<R as Rule>::Options: Default,
{
if let Some(node) = params.query.downcast_ref::<SyntaxNode<RuleLanguage<R>>>() {
if state.suppressions.inner.contains(node) {
return Ok(());
}
}
// SAFETY: The rule should never get executed in the first place
// if the query doesn't match
let query_result = params.query.downcast_ref().unwrap();
let query_result = <R::Query as Queryable>::unwrap_match(params.services, query_result);
let globals = params.options.globals();
let options = params.options.rule_options::<R>().unwrap_or_default();
let ctx = match RuleContext::new(
&query_result,
params.root,
params.services,
&globals,
¶ms.options.file_path,
&options,
) {
Ok(ctx) => ctx,
Err(error) => return Err(error),
};
for result in R::run(&ctx) {
let text_range =
R::text_range(&ctx, &result).unwrap_or_else(|| params.query.text_range());
R::suppressed_nodes(&ctx, &result, &mut state.suppressions);
let signal = Box::new(RuleSignal::<R>::new(
params.root,
query_result.clone(),
result,
params.services,
params.apply_suppression_comment,
params.options,
));
params.signal_queue.push(SignalEntry {
signal,
rule: RuleKey::rule::<R>(),
text_range,
});
}
Ok(())
}
Self {
run: run::<R>,
state_index,
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/options.rs | crates/rome_analyze/src/options.rs | use crate::{Rule, RuleKey};
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt::Debug;
use std::path::PathBuf;
/// A convenient new type data structure to store the options that belong to a rule
#[derive(Debug)]
pub struct RuleOptions((TypeId, Box<dyn Any>));
impl RuleOptions {
/// It returns the deserialized rule option
pub fn value<O: 'static>(&self) -> &O {
let (type_id, value) = &self.0;
let current_id = TypeId::of::<O>();
debug_assert_eq!(type_id, ¤t_id);
// SAFETY: the code should fail when asserting the types.
// If the code throws an error here, it means that the developer didn't test
// the rule with the options
value.downcast_ref::<O>().unwrap()
}
/// Creates a new [RuleOptions]
pub fn new<O: 'static>(options: O) -> Self {
Self((TypeId::of::<O>(), Box::new(options)))
}
}
/// A convenient new type data structure to insert and get rules
#[derive(Debug, Default)]
pub struct AnalyzerRules(HashMap<RuleKey, RuleOptions>);
impl AnalyzerRules {
/// It tracks the options of a specific rule
pub fn push_rule(&mut self, rule_key: RuleKey, options: RuleOptions) {
self.0.insert(rule_key, options);
}
/// It retrieves the options of a stored rule, given its name
pub fn get_rule_options<O: 'static>(&self, rule_key: &RuleKey) -> Option<&O> {
self.0.get(rule_key).map(|o| o.value::<O>())
}
}
/// A data structured derived from the `rome.json` file
#[derive(Debug, Default)]
pub struct AnalyzerConfiguration {
/// A list of rules and their options
pub rules: AnalyzerRules,
/// A collections of bindings that the analyzers should consider as "external".
///
/// For example, lint rules should ignore them.
pub globals: Vec<String>,
}
/// A set of information useful to the analyzer infrastructure
#[derive(Debug, Default)]
pub struct AnalyzerOptions {
/// A data structured derived from the [`rome.json`] file
pub configuration: AnalyzerConfiguration,
/// The file that is being analyzed
pub file_path: PathBuf,
}
impl AnalyzerOptions {
pub fn globals(&self) -> Vec<&str> {
self.configuration
.globals
.iter()
.map(|global| global.as_str())
.collect()
}
pub fn rule_options<R: 'static>(&self) -> Option<R::Options>
where
R: Rule,
R::Options: Clone,
{
self.configuration
.rules
.get_rule_options::<R::Options>(&RuleKey::rule::<R>())
.map(R::Options::clone)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/query.rs | crates/rome_analyze/src/query.rs | use std::any::TypeId;
use rome_rowan::{Language, SyntaxKindSet, TextRange};
use crate::{registry::Phase, services::FromServices, Phases, ServiceBag, Visitor};
/// Trait implemented for types that lint rules can query in order to emit diagnostics or code actions.
pub trait Queryable: Sized {
type Input: QueryMatch;
type Output;
type Language: Language;
type Services: FromServices + Phase;
/// Registers one or more [Visitor] that will emit `Self::Input` query
/// matches during the analyzer run
fn build_visitor(
analyzer: &mut impl AddVisitor<Self::Language>,
root: &<Self::Language as Language>::Root,
);
/// Returns the type of query matches this [Queryable] expects as inputs
///
/// Unless your custom queryable needs to match on a specific
/// [SyntaxKindSet], you should not override the default implementation of
/// this method
fn key() -> QueryKey<Self::Language> {
QueryKey::TypeId(TypeId::of::<Self::Input>())
}
/// Unwrap an instance of `Self` from a [QueryMatch].
///
/// ## Panics
///
/// If the [QueryMatch] variant of `query` doesn't match `Self::KEY`
fn unwrap_match(services: &ServiceBag, query: &Self::Input) -> Self::Output;
}
/// This trait is implemented on all types that supports the registration of [Visitor]
pub trait AddVisitor<L: Language> {
/// Registers a [Visitor] for a given `phase`
fn add_visitor<F, V>(&mut self, phase: Phases, visitor: F)
where
F: FnOnce() -> V,
V: Visitor<Language = L> + 'static;
}
/// Marker trait implemented for all the types analyzer visitors may emit
pub trait QueryMatch: 'static {
fn text_range(&self) -> TextRange;
}
/// Represents which type a given [Queryable] type can match, either a specific
/// subset of syntax node kinds or any generic type
pub enum QueryKey<L: Language> {
Syntax(SyntaxKindSet<L>),
TypeId(TypeId),
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/matcher.rs | crates/rome_analyze/src/matcher.rs | use crate::{
AnalyzerOptions, AnalyzerSignal, Phases, QueryMatch, Rule, RuleFilter, RuleGroup, ServiceBag,
SuppressionCommentEmitter,
};
use rome_rowan::{Language, TextRange};
use std::{
any::{Any, TypeId},
cmp::Ordering,
collections::BinaryHeap,
};
/// The [QueryMatcher] trait is responsible of running lint rules on
/// [QueryMatch](crate::QueryMatch) instances emitted by the various
/// [Visitor](crate::Visitor) and push signals wrapped in [SignalEntry]
/// to the signal queue
pub trait QueryMatcher<L: Language> {
/// Execute a single query match
fn match_query(&mut self, params: MatchQueryParams<L>);
}
/// Parameters provided to [QueryMatcher::match_query] and require to run lint rules
pub struct MatchQueryParams<'phase, 'query, L: Language> {
pub phase: Phases,
pub root: &'phase L::Root,
pub query: Query,
pub services: &'phase ServiceBag,
pub signal_queue: &'query mut BinaryHeap<SignalEntry<'phase, L>>,
pub apply_suppression_comment: SuppressionCommentEmitter<L>,
pub options: &'phase AnalyzerOptions,
}
/// Wrapper type for a [QueryMatch]
///
/// This type is functionally equivalent to `Box<dyn QueryMatch + Any>`, it
/// emulates dynamic dispatch for both traits and allows downcasting to a
/// reference or owned type.
pub struct Query {
data: Box<dyn Any>,
read_text_range: fn(&dyn Any) -> TextRange,
}
impl Query {
/// Construct a new [Query] instance from a [QueryMatch]
pub fn new<T: QueryMatch>(data: T) -> Self {
Self {
data: Box::new(data),
read_text_range: |query| query.downcast_ref::<T>().unwrap().text_range(),
}
}
/// Attempt to downcast the query to an owned type.
pub fn downcast<T: QueryMatch>(self) -> Option<T> {
Some(*self.data.downcast::<T>().ok()?)
}
/// Attempt to downcast the query to a reference type.
pub fn downcast_ref<T: QueryMatch>(&self) -> Option<&T> {
self.data.downcast_ref::<T>()
}
/// Returns the [TypeId] of this query, equivalent to calling [Any::type_id].
pub(crate) fn type_id(&self) -> TypeId {
self.data.as_ref().type_id()
}
/// Returns the [TextRange] of this query, equivalent to calling [QueryMatch::text_range].
pub(crate) fn text_range(&self) -> TextRange {
(self.read_text_range)(self.data.as_ref())
}
}
/// Opaque identifier for a group of rule
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct GroupKey {
group: &'static str,
}
impl GroupKey {
pub(crate) fn new(group: &'static str) -> Self {
Self { group }
}
pub fn group<G: RuleGroup>() -> Self {
Self::new(G::NAME)
}
}
impl From<GroupKey> for RuleFilter<'static> {
fn from(key: GroupKey) -> Self {
RuleFilter::Group(key.group)
}
}
/// Opaque identifier for a single rule
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RuleKey {
group: &'static str,
rule: &'static str,
}
impl RuleKey {
pub fn new(group: &'static str, rule: &'static str) -> Self {
Self { group, rule }
}
pub fn rule<R: Rule>() -> Self {
Self::new(<R::Group as RuleGroup>::NAME, R::METADATA.name)
}
pub fn group(&self) -> &'static str {
self.group
}
pub fn rule_name(&self) -> &'static str {
self.rule
}
}
impl From<RuleKey> for RuleFilter<'static> {
fn from(key: RuleKey) -> Self {
RuleFilter::Rule(key.group, key.rule)
}
}
impl PartialEq<RuleKey> for RuleFilter<'static> {
fn eq(&self, other: &RuleKey) -> bool {
match *self {
RuleFilter::Group(group) => group == other.group,
RuleFilter::Rule(group, rule) => group == other.group && rule == other.rule,
}
}
}
/// Entry for a pending signal in the `signal_queue`
pub struct SignalEntry<'phase, L: Language> {
/// Boxed analyzer signal to be emitted
pub signal: Box<dyn AnalyzerSignal<L> + 'phase>,
/// Unique identifier for the rule that emitted this signal
pub rule: RuleKey,
/// Text range in the document this signal covers
pub text_range: TextRange,
}
// SignalEntry is ordered based on the starting point of its `text_range`
impl<'phase, L: Language> Ord for SignalEntry<'phase, L> {
fn cmp(&self, other: &Self) -> Ordering {
other.text_range.start().cmp(&self.text_range.start())
}
}
impl<'phase, L: Language> PartialOrd for SignalEntry<'phase, L> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'phase, L: Language> Eq for SignalEntry<'phase, L> {}
impl<'phase, L: Language> PartialEq for SignalEntry<'phase, L> {
fn eq(&self, other: &Self) -> bool {
self.text_range.start() == other.text_range.start()
}
}
/// Adapter type wrapping a [QueryMatcher] type with a function that can be
/// used to inspect the query matches emitted by the analyzer
pub struct InspectMatcher<F, I> {
func: F,
inner: I,
}
impl<F, I> InspectMatcher<F, I> {
/// Create a new instance of [InspectMatcher] from an existing [QueryMatcher]
/// object and an inspection function
pub fn new<L>(inner: I, func: F) -> Self
where
L: Language,
F: FnMut(&MatchQueryParams<L>),
I: QueryMatcher<L>,
{
Self { func, inner }
}
}
impl<L, F, I> QueryMatcher<L> for InspectMatcher<F, I>
where
L: Language,
F: FnMut(&MatchQueryParams<L>),
I: QueryMatcher<L>,
{
fn match_query(&mut self, params: MatchQueryParams<L>) {
(self.func)(¶ms);
self.inner.match_query(params);
}
}
#[cfg(test)]
mod tests {
use super::MatchQueryParams;
use crate::{
signals::DiagnosticSignal, Analyzer, AnalyzerContext, AnalyzerSignal, ControlFlow,
MetadataRegistry, Never, Phases, QueryMatcher, RuleKey, ServiceBag, SignalEntry,
SyntaxVisitor,
};
use crate::{AnalyzerOptions, SuppressionKind};
use rome_diagnostics::{category, DiagnosticExt};
use rome_diagnostics::{Diagnostic, Severity};
use rome_rowan::{
raw_language::{RawLanguage, RawLanguageKind, RawLanguageRoot, RawSyntaxTreeBuilder},
AstNode, SyntaxNode, TextRange, TextSize, TriviaPiece, TriviaPieceKind,
};
use std::convert::Infallible;
struct SuppressionMatcher;
#[derive(Debug, Diagnostic)]
#[diagnostic(category = "args/fileNotFound", message = "test_suppression")]
struct TestDiagnostic {
#[location(span)]
span: TextRange,
}
impl QueryMatcher<RawLanguage> for SuppressionMatcher {
/// Emits a warning diagnostic for all literal expressions
fn match_query(&mut self, params: MatchQueryParams<RawLanguage>) {
let node = params.query.downcast::<SyntaxNode<RawLanguage>>().unwrap();
if node.kind() != RawLanguageKind::LITERAL_EXPRESSION {
return;
}
let span = node.text_trimmed_range();
params.signal_queue.push(SignalEntry {
signal: Box::new(DiagnosticSignal::new(move || TestDiagnostic { span })),
rule: RuleKey::new("group", "rule"),
text_range: span,
});
}
}
#[test]
fn suppressions() {
let root = {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::ROOT);
builder.start_node(RawLanguageKind::SEPARATED_EXPRESSION_LIST);
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token_with_trivia(
RawLanguageKind::STRING_TOKEN,
"//group\n\"warn_here\"",
&[
TriviaPiece::new(TriviaPieceKind::SingleLineComment, 7),
TriviaPiece::new(TriviaPieceKind::Newline, 1),
],
&[],
);
builder.finish_node();
builder.token_with_trivia(
RawLanguageKind::SEMICOLON_TOKEN,
";\n",
&[],
&[TriviaPiece::new(TriviaPieceKind::Newline, 1)],
);
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token_with_trivia(
RawLanguageKind::STRING_TOKEN,
"//group/rule\n\"warn_here\"",
&[
TriviaPiece::new(TriviaPieceKind::SingleLineComment, 12),
TriviaPiece::new(TriviaPieceKind::Newline, 1),
],
&[],
);
builder.finish_node();
builder.token_with_trivia(
RawLanguageKind::SEMICOLON_TOKEN,
";\n",
&[],
&[TriviaPiece::new(TriviaPieceKind::Newline, 1)],
);
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token_with_trivia(
RawLanguageKind::STRING_TOKEN,
"//unknown_group\n\"warn_here\"",
&[
TriviaPiece::new(TriviaPieceKind::SingleLineComment, 15),
TriviaPiece::new(TriviaPieceKind::Newline, 1),
],
&[],
);
builder.finish_node();
builder.token_with_trivia(
RawLanguageKind::SEMICOLON_TOKEN,
";\n",
&[],
&[TriviaPiece::new(TriviaPieceKind::Newline, 1)],
);
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token_with_trivia(
RawLanguageKind::STRING_TOKEN,
"//group/unknown_rule\n\"warn_here\"",
&[
TriviaPiece::new(TriviaPieceKind::SingleLineComment, 20),
TriviaPiece::new(TriviaPieceKind::Newline, 1),
],
&[],
);
builder.finish_node();
builder.token_with_trivia(
RawLanguageKind::SEMICOLON_TOKEN,
";\n",
&[],
&[TriviaPiece::new(TriviaPieceKind::Newline, 1)],
);
builder.token_with_trivia(
RawLanguageKind::SEMICOLON_TOKEN,
"//group/rule\n;\n",
&[
TriviaPiece::new(TriviaPieceKind::SingleLineComment, 12),
TriviaPiece::new(TriviaPieceKind::Newline, 1),
],
&[TriviaPiece::new(TriviaPieceKind::Newline, 1)],
);
builder.finish_node();
builder.finish_node();
RawLanguageRoot::unwrap_cast(builder.finish())
};
let mut diagnostics = Vec::new();
let mut emit_signal = |signal: &dyn AnalyzerSignal<RawLanguage>| -> ControlFlow<Never> {
let diag = signal.diagnostic().expect("diagnostic");
let range = diag.get_span().expect("range");
let error = diag.with_severity(Severity::Warning);
let code = error.category().expect("code");
diagnostics.push((code, range));
ControlFlow::Continue(())
};
fn parse_suppression_comment(
comment: &'_ str,
) -> Vec<Result<SuppressionKind<'_>, Infallible>> {
comment
.trim_start_matches("//")
.split(' ')
.map(SuppressionKind::Rule)
.map(Ok)
.collect()
}
let mut metadata = MetadataRegistry::default();
metadata.insert_rule("group", "rule");
let mut analyzer = Analyzer::new(
&metadata,
SuppressionMatcher,
parse_suppression_comment,
|_| unreachable!(),
&mut emit_signal,
);
analyzer.add_visitor(Phases::Syntax, Box::<SyntaxVisitor<RawLanguage>>::default());
let ctx: AnalyzerContext<RawLanguage> = AnalyzerContext {
root,
range: None,
services: ServiceBag::default(),
options: &AnalyzerOptions::default(),
};
let result: Option<Never> = analyzer.run(ctx);
assert!(result.is_none());
assert_eq!(
diagnostics.as_slice(),
&[
(
category!("suppressions/unknownGroup"),
TextRange::new(TextSize::from(47), TextSize::from(62))
),
(
category!("args/fileNotFound"),
TextRange::new(TextSize::from(63), TextSize::from(74))
),
(
category!("suppressions/unknownRule"),
TextRange::new(TextSize::from(76), TextSize::from(96))
),
(
category!("args/fileNotFound"),
TextRange::new(TextSize::from(97), TextSize::from(108))
),
(
category!("suppressions/unused"),
TextRange::new(TextSize::from(110), TextSize::from(122))
),
]
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/context.rs | crates/rome_analyze/src/context.rs | use crate::{registry::RuleRoot, FromServices, Queryable, Rule, RuleKey, ServiceBag};
use rome_diagnostics::{Error, Result};
use std::ops::Deref;
use std::path::Path;
type RuleQueryResult<R> = <<R as Rule>::Query as Queryable>::Output;
type RuleServiceBag<R> = <<R as Rule>::Query as Queryable>::Services;
pub struct RuleContext<'a, R>
where
R: ?Sized + Rule,
{
query_result: &'a RuleQueryResult<R>,
root: &'a RuleRoot<R>,
bag: &'a ServiceBag,
services: RuleServiceBag<R>,
globals: &'a [&'a str],
file_path: &'a Path,
options: &'a R::Options,
}
impl<'a, R> RuleContext<'a, R>
where
R: Rule + Sized + 'static,
{
pub fn new(
query_result: &'a RuleQueryResult<R>,
root: &'a RuleRoot<R>,
services: &'a ServiceBag,
globals: &'a [&'a str],
file_path: &'a Path,
options: &'a R::Options,
) -> Result<Self, Error> {
let rule_key = RuleKey::rule::<R>();
Ok(Self {
query_result,
root,
bag: services,
services: FromServices::from_services(&rule_key, services)?,
globals,
file_path,
options,
})
}
pub fn query(&self) -> &RuleQueryResult<R> {
self.query_result
}
/// Returns a clone of the AST root
pub fn root(&self) -> RuleRoot<R> {
self.root.clone()
}
/// It retrieves the options that belong to a rule, if they exist.
///
/// In order to retrieve a typed data structure, you have to create a deserializable
/// data structure and define it inside the generic type `type Options` of the [Rule]
///
/// ## Examples
///
/// ```rust,ignore
/// use rome_analyze::{declare_rule, Rule, RuleCategory, RuleMeta, RuleMetadata};
/// use rome_analyze::context::RuleContext;
/// use serde::Deserialize;
/// declare_rule! {
/// /// Some doc
/// pub(crate) Name {
/// version: "0.0.0",
/// name: "name",
/// recommended: true,
/// }
/// }
///
/// #[derive(Deserialize)]
/// struct RuleOptions {}
///
/// impl Rule for Name {
/// const CATEGORY: RuleCategory = RuleCategory::Lint;
/// type Query = ();
/// type State = ();
/// type Signals = ();
/// type Options = RuleOptions;
///
/// fn run(ctx: &RuleContext<Self>) -> Self::Signals {
/// if let Some(options) = ctx.options() {
/// // do something with the options now
/// }
/// }
/// }
/// ```
pub fn options(&self) -> &R::Options {
self.options
}
/// Checks whether the provided text belongs to globals
pub fn is_global(&self, text: &str) -> bool {
self.globals.contains(&text)
}
/// Returns the source type of the current file
pub fn source_type<T: 'static>(&self) -> &T {
self.bag
.get_service::<T>()
.expect("Source type is not registered")
}
/// The file path of the current file
pub fn file_path(&self) -> &Path {
self.file_path
}
}
impl<'a, R> Deref for RuleContext<'a, R>
where
R: Rule,
{
type Target = RuleServiceBag<R>;
fn deref(&self) -> &Self::Target {
&self.services
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/rule.rs | crates/rome_analyze/src/rule.rs | use crate::categories::{ActionCategory, RuleCategory};
use crate::context::RuleContext;
use crate::registry::{RegistryVisitor, RuleLanguage, RuleSuppressions};
use crate::{
Phase, Phases, Queryable, SuppressionCommentEmitter, SuppressionCommentEmitterPayload,
};
use rome_console::fmt::Display;
use rome_console::{markup, MarkupBuf};
use rome_diagnostics::advice::CodeSuggestionAdvice;
use rome_diagnostics::location::AsSpan;
use rome_diagnostics::Applicability;
use rome_diagnostics::{
Advices, Category, Diagnostic, DiagnosticTags, Location, LogCategory, MessageAndDescription,
Visit,
};
use rome_rowan::{AstNode, BatchMutation, BatchMutationExt, Language, TextRange};
use std::fmt::Debug;
/// Static metadata containing information about a rule
pub struct RuleMetadata {
/// It marks if a rule is deprecated, and if so a reason has to be provided.
pub deprecated: Option<&'static str>,
/// The version when the rule was implemented
pub version: &'static str,
/// The name of this rule, displayed in the diagnostics it emits
pub name: &'static str,
/// The content of the documentation comments for this rule
pub docs: &'static str,
/// Whether a rule is recommended or not
pub recommended: bool,
}
impl RuleMetadata {
pub const fn new(version: &'static str, name: &'static str, docs: &'static str) -> Self {
Self {
deprecated: None,
version,
name,
docs,
recommended: false,
}
}
pub const fn recommended(mut self, recommended: bool) -> Self {
self.recommended = recommended;
self
}
pub const fn deprecated(mut self, deprecated: &'static str) -> Self {
self.deprecated = Some(deprecated);
self
}
}
pub trait RuleMeta {
type Group: RuleGroup;
const METADATA: RuleMetadata;
}
/// This macro is used to declare an analyzer rule type, and implement the
// [RuleMeta] trait for it
/// # Example
///
/// The macro itself expect the following syntax:
///
/// ```rust,ignore
///use rome_analyze::declare_rule;
///
/// declare_rule! {
/// /// Documentation
/// pub(crate) ExampleRule {
/// version: "0.7.0",
/// name: "ruleName",
/// recommended: false,
/// }
/// }
/// ```
///
/// Check [crate](module documentation) for a better
/// understanding of how the macro works
#[macro_export]
macro_rules! declare_rule {
( $( #[doc = $doc:literal] )+ $vis:vis $id:ident {
version: $version:literal,
name: $name:tt,
$( $key:ident: $value:expr, )*
} ) => {
$( #[doc = $doc] )*
$vis enum $id {}
impl $crate::RuleMeta for $id {
type Group = super::Group;
const METADATA: $crate::RuleMetadata =
$crate::RuleMetadata::new($version, $name, concat!( $( $doc, "\n", )* )) $( .$key($value) )*;
}
// Declare a new `rule_category!` macro in the module context that
// expands to the category of this rule
// This is implemented by calling the `group_category!` macro from the
// parent module (that should be declared by a call to `declare_group!`)
// and providing it with the name of this rule as a string literal token
#[allow(unused_macros)]
macro_rules! rule_category {
() => { super::group_category!( $name ) };
}
};
}
/// A rule group is a collection of rules under a given name, serving as a
/// "namespace" for lint rules and allowing the entire set of rules to be
/// disabled at once
pub trait RuleGroup {
type Language: Language;
type Category: GroupCategory;
/// The name of this group, displayed in the diagnostics emitted by its rules
const NAME: &'static str;
/// Register all the rules belonging to this group into `registry`
fn record_rules<V: RegistryVisitor<Self::Language> + ?Sized>(registry: &mut V);
}
/// This macro is used by the codegen script to declare an analyzer rule group,
/// and implement the [RuleGroup] trait for it
#[macro_export]
macro_rules! declare_group {
( $vis:vis $id:ident { name: $name:tt, rules: [ $( $( $rule:ident )::* , )* ] } ) => {
$vis enum $id {}
impl $crate::RuleGroup for $id {
type Language = <( $( $( $rule )::* , )* ) as $crate::GroupLanguage>::Language;
type Category = super::Category;
const NAME: &'static str = $name;
fn record_rules<V: $crate::RegistryVisitor<Self::Language> + ?Sized>(registry: &mut V) {
$( registry.record_rule::<$( $rule )::*>(); )*
}
}
pub(self) use $id as Group;
// Declare a `group_category!` macro in the context of this module (and
// all its children). This macro takes the name of a rule as a string
// literal token and expands to the category of the lint rule with this
// name within this group.
// This is implemented by calling the `category_concat!` macro with the
// "lint" prefix, the name of this group, and the rule name argument
#[allow(unused_macros)]
macro_rules! group_category {
( $rule_name:tt ) => { $crate::category_concat!( "lint", $name, $rule_name ) };
}
// Re-export the macro for child modules, so `declare_rule!` can access
// the category of its parent group by using the `super` module
pub(self) use group_category;
};
}
/// A group category is a collection of rule groups under a given category ID,
/// serving as a broad classification on the kind of diagnostic or code action
/// these rule emit, and allowing whole categories of rules to be disabled at
/// once depending on the kind of analysis being performed
pub trait GroupCategory {
type Language: Language;
/// The category ID used for all groups and rule belonging to this category
const CATEGORY: RuleCategory;
/// Register all the groups belonging to this category into `registry`
fn record_groups<V: RegistryVisitor<Self::Language> + ?Sized>(registry: &mut V);
}
#[macro_export]
macro_rules! declare_category {
( $vis:vis $id:ident { kind: $kind:ident, groups: [ $( $( $group:ident )::* , )* ] } ) => {
$vis enum $id {}
impl $crate::GroupCategory for $id {
type Language = <( $( $( $group )::* , )* ) as $crate::CategoryLanguage>::Language;
const CATEGORY: $crate::RuleCategory = $crate::RuleCategory::$kind;
fn record_groups<V: $crate::RegistryVisitor<Self::Language> + ?Sized>(registry: &mut V) {
$( registry.record_group::<$( $group )::*>(); )*
}
}
pub(self) use $id as Category;
};
}
/// This trait is implemented for tuples of [Rule] types of size 1 to 29 if the
/// query type of all the rules in the tuple share the same associated
/// [Language] (which is then aliased as the `Language` associated type on
/// [GroupLanguage] itself). It is used to ensure all the rules in a given
/// group are all querying the same underlying language
pub trait GroupLanguage {
type Language: Language;
}
/// This trait is implemented for tuples of [Rule] types of size 1 to 29 if the
/// language of all the groups in the tuple share the same associated
/// [Language] (which is then aliased as the `Language` associated type on
/// [CategoryLanguage] itself). It is used to ensure all the groups in a given
/// category are all querying the same underlying language
pub trait CategoryLanguage {
type Language: Language;
}
/// Helper macro for implementing [GroupLanguage] on a large number of tuple types at once
macro_rules! impl_group_language {
( $head:ident $( , $rest:ident )* ) => {
impl<$head $( , $rest )*> GroupLanguage for ($head, $( $rest ),*)
where
$head: Rule $( , $rest: Rule, <$rest as Rule>::Query: Queryable<Language = RuleLanguage<$head>> )*
{
type Language = RuleLanguage<$head>;
}
impl<$head $( , $rest )*> CategoryLanguage for ($head, $( $rest ),*)
where
$head: RuleGroup $( , $rest: RuleGroup<Language = <$head as RuleGroup>::Language> )*
{
type Language = <$head as RuleGroup>::Language;
}
impl_group_language!( $( $rest ),* );
};
() => {};
}
impl_group_language!(
T00, T01, T02, T03, T04, T05, T06, T07, T08, T09, T10, T11, T12, T13, T14, T15, T16, T17, T18,
T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37,
T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50, T51, T52, T53, T54, T55, T56,
T57, T58, T59, T60, T61, T62, T63, T64, T65, T66, T67, T68, T69, T70, T71, T72, T73, T74, T75,
T76, T77, T78, T79, T80, T81, T82, T83, T84, T85, T86, T87, T88, T89
);
/// Trait implemented by all analysis rules: declares interest to a certain AstNode type,
/// and a callback function to be executed on all nodes matching the query to possibly
/// raise an analysis event
pub trait Rule: RuleMeta + Sized {
/// The type of AstNode this rule is interested in
type Query: Queryable;
/// A generic type that will be kept in memory between a call to `run` and
/// subsequent executions of `diagnostic` or `action`, allows the rule to
/// hold some temporary state between the moment a signal is raised and
/// when a diagnostic or action needs to be built
type State;
/// An iterator type returned by `run` to yield zero or more signals to the
/// analyzer
type Signals: IntoIterator<Item = Self::State>;
/// The options that belong to a rule
type Options: Default + Clone + Debug;
fn phase() -> Phases {
<<<Self as Rule>::Query as Queryable>::Services as Phase>::phase()
}
/// This function is called once for each node matching `Query` in the tree
/// being analyzed. If it returns `Some` the state object will be wrapped
/// in a generic `AnalyzerSignal`, and the consumer of the analyzer may call
/// `diagnostic` or `action` on it
fn run(ctx: &RuleContext<Self>) -> Self::Signals;
/// Used by the analyzer to associate a range of source text to a signal in
/// order to support suppression comments.
///
/// If this function returns [None], the range of the query node will be used instead
///
/// The default implementation returns the range of `Self::diagnostic`, and
/// should return the correct value for most rules however you may want to
/// override this if generating a diagnostic for this rule requires heavy
/// processing and the range could be determined through a faster path
fn text_range(ctx: &RuleContext<Self>, state: &Self::State) -> Option<TextRange> {
Self::diagnostic(ctx, state).and_then(|diag| diag.span())
}
/// Allows the rule to suppress a set of syntax nodes to prevent them from
/// matching the `Query`. This is useful for rules that implement a code
/// action that recursively modifies multiple nodes at once, this hook
/// allows these rules to avoid matching on those nodes again.
///
/// # Example
///
/// ```ignore
/// impl Rule for SimplifyExpression {
/// type Query = BinaryExpression;
///
/// fn run(ctx: &RuleContext<Self>) -> Self::Signals {
/// // Recursively check this expression and its children for simplification
/// // opportunities
/// check_can_simplify(ctx.query())
/// }
///
/// fn suppressed_nodes(
/// _ctx: &RuleContext<Self>,
/// state: &Self::State,
/// suppressions: &mut RuleSuppressions<RuleLanguage<Self>>
/// ) {
/// // Prevent this rule from matching again on nodes that were already checked by
/// // `check_can_simplify`
/// for node in &state.nodes {
/// suppressions.suppress_node(node.clone());
/// }
/// }
/// }
/// ```
fn suppressed_nodes(
ctx: &RuleContext<Self>,
state: &Self::State,
suppressions: &mut RuleSuppressions<RuleLanguage<Self>>,
) {
let (..) = (ctx, state, suppressions);
}
/// Called by the consumer of the analyzer to try to generate a diagnostic
/// from a signal raised by `run`
///
/// The default implementation returns None
fn diagnostic(_ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
None
}
/// Called by the consumer of the analyzer to try to generate a code action
/// from a signal raised by `run`
///
/// The default implementation returns None
fn action(
ctx: &RuleContext<Self>,
state: &Self::State,
) -> Option<RuleAction<RuleLanguage<Self>>> {
let (..) = (ctx, state);
None
}
/// Create a code action that allows to suppress the rule. The function
/// returns the node to which the suppression comment is applied.
fn suppress(
ctx: &RuleContext<Self>,
text_range: &TextRange,
apply_suppression_comment: SuppressionCommentEmitter<RuleLanguage<Self>>,
) -> Option<SuppressAction<RuleLanguage<Self>>>
where
Self: 'static,
{
// if the rule belongs to `Lint`, we auto generate an action to suppress the rule
if <Self::Group as RuleGroup>::Category::CATEGORY == RuleCategory::Lint {
let rule_category = format!(
"lint/{}/{}",
<Self::Group as RuleGroup>::NAME,
Self::METADATA.name
);
let suppression_text = format!("rome-ignore {}", rule_category);
let root = ctx.root();
let token = root.syntax().token_at_offset(text_range.start());
let mut mutation = root.begin();
apply_suppression_comment(SuppressionCommentEmitterPayload {
suppression_text: suppression_text.as_str(),
mutation: &mut mutation,
token_offset: token,
diagnostic_text_range: text_range,
});
Some(SuppressAction {
mutation,
message: markup! { "Suppress rule " {rule_category} }.to_owned(),
})
} else {
None
}
}
/// Returns a mutation to apply to the code
fn transform(
_ctx: &RuleContext<Self>,
_state: &Self::State,
) -> Option<BatchMutation<RuleLanguage<Self>>> {
None
}
}
/// Diagnostic object returned by a single analysis rule
#[derive(Debug, Diagnostic)]
pub struct RuleDiagnostic {
#[category]
pub(crate) category: &'static Category,
#[location(span)]
pub(crate) span: Option<TextRange>,
#[message]
#[description]
pub(crate) message: MessageAndDescription,
#[tags]
pub(crate) tags: DiagnosticTags,
#[advice]
pub(crate) rule_advice: RuleAdvice,
}
#[derive(Debug, Default)]
/// It contains possible advices to show when printing a diagnostic that belong to the rule
pub struct RuleAdvice {
pub(crate) details: Vec<Detail>,
pub(crate) notes: Vec<(LogCategory, MarkupBuf)>,
pub(crate) suggestion_list: Option<SuggestionList>,
pub(crate) code_suggestion_list: Vec<CodeSuggestionAdvice<MarkupBuf>>,
}
#[derive(Debug, Default)]
pub struct SuggestionList {
pub(crate) message: MarkupBuf,
pub(crate) list: Vec<MarkupBuf>,
}
impl Advices for RuleAdvice {
fn record(&self, visitor: &mut dyn Visit) -> std::io::Result<()> {
for detail in &self.details {
visitor.record_log(
detail.log_category,
&markup! { {detail.message} }.to_owned(),
)?;
visitor.record_frame(Location::builder().span(&detail.range).build())?;
}
// we then print notes
for (log_category, note) in &self.notes {
visitor.record_log(*log_category, &markup! { {note} }.to_owned())?;
}
if let Some(suggestion_list) = &self.suggestion_list {
visitor.record_log(
LogCategory::Info,
&markup! { {suggestion_list.message} }.to_owned(),
)?;
let list: Vec<_> = suggestion_list
.list
.iter()
.map(|suggestion| suggestion as &dyn Display)
.collect();
visitor.record_list(&list)?;
}
// finally, we print possible code suggestions on how to fix the issue
for suggestion in &self.code_suggestion_list {
suggestion.record(visitor)?;
}
Ok(())
}
}
#[derive(Debug)]
pub struct Detail {
pub log_category: LogCategory,
pub message: MarkupBuf,
pub range: Option<TextRange>,
}
impl RuleDiagnostic {
/// Creates a new [`RuleDiagnostic`] with a severity and title that will be
/// used in a builder-like way to modify labels.
pub fn new(category: &'static Category, span: impl AsSpan, title: impl Display) -> Self {
let message = markup!({ title }).to_owned();
Self {
category,
span: span.as_span(),
message: MessageAndDescription::from(message),
tags: DiagnosticTags::empty(),
rule_advice: RuleAdvice::default(),
}
}
/// Set an explicit plain-text summary for this diagnostic.
pub fn description(mut self, summary: impl Into<String>) -> Self {
self.message.set_description(summary.into());
self
}
/// Marks this diagnostic as deprecated code, which will
/// be displayed in the language server.
///
/// This does not have any influence on the diagnostic rendering.
pub fn deprecated(mut self) -> Self {
self.tags |= DiagnosticTags::DEPRECATED_CODE;
self
}
/// Marks this diagnostic as unnecessary code, which will
/// be displayed in the language server.
///
/// This does not have any influence on the diagnostic rendering.
pub fn unnecessary(mut self) -> Self {
self.tags |= DiagnosticTags::UNNECESSARY_CODE;
self
}
/// Attaches a label to this [`RuleDiagnostic`].
///
/// The given span has to be in the file that was provided while creating this [`RuleDiagnostic`].
pub fn label(mut self, span: impl AsSpan, msg: impl Display) -> Self {
self.rule_advice.details.push(Detail {
log_category: LogCategory::Info,
message: markup!({ msg }).to_owned(),
range: span.as_span(),
});
self
}
/// Attaches a detailed message to this [`RuleDiagnostic`].
pub fn detail(self, span: impl AsSpan, msg: impl Display) -> Self {
self.label(span, msg)
}
/// Adds a footer to this [`RuleDiagnostic`], which will be displayed under the actual error.
fn footer(mut self, log_category: LogCategory, msg: impl Display) -> Self {
self.rule_advice
.notes
.push((log_category, markup!({ msg }).to_owned()));
self
}
/// Adds a footer to this [`RuleDiagnostic`], with the `Info` log category.
pub fn note(self, msg: impl Display) -> Self {
self.footer(LogCategory::Info, msg)
}
/// It creates a new footer note which contains a message and a list of possible suggestions.
/// Useful when there's need to suggest a list of things inside a diagnostic.
pub fn footer_list(mut self, message: impl Display, list: &[impl Display]) -> Self {
if !list.is_empty() {
self.rule_advice.suggestion_list = Some(SuggestionList {
message: markup! { {message} }.to_owned(),
list: list
.iter()
.map(|msg| markup! { {msg} }.to_owned())
.collect(),
});
}
self
}
/// Adds a footer to this [`RuleDiagnostic`], with the `Warn` severity.
pub fn warning(self, msg: impl Display) -> Self {
self.footer(LogCategory::Warn, msg)
}
pub(crate) fn span(&self) -> Option<TextRange> {
self.span
}
pub fn advices(&self) -> &RuleAdvice {
&self.rule_advice
}
}
/// Code Action object returned by a single analysis rule
pub struct RuleAction<L: Language> {
pub category: ActionCategory,
pub applicability: Applicability,
pub message: MarkupBuf,
pub mutation: BatchMutation<L>,
}
/// An action meant to suppress a lint rule
#[derive(Clone)]
pub struct SuppressAction<L: Language> {
pub message: MarkupBuf,
pub mutation: BatchMutation<L>,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_analyze/src/signals.rs | crates/rome_analyze/src/signals.rs | use crate::categories::SUPPRESSION_ACTION_CATEGORY;
use crate::{
categories::ActionCategory,
context::RuleContext,
registry::{RuleLanguage, RuleRoot},
rule::Rule,
AnalyzerDiagnostic, AnalyzerOptions, Queryable, RuleGroup, ServiceBag,
SuppressionCommentEmitter,
};
use rome_console::MarkupBuf;
use rome_diagnostics::{advice::CodeSuggestionAdvice, Applicability, CodeSuggestion, Error};
use rome_rowan::{BatchMutation, Language};
use std::borrow::Cow;
use std::iter::FusedIterator;
use std::marker::PhantomData;
use std::vec::IntoIter;
/// Event raised by the analyzer when a [Rule](crate::Rule)
/// emits a diagnostic, a code action, or both
pub trait AnalyzerSignal<L: Language> {
fn diagnostic(&self) -> Option<AnalyzerDiagnostic>;
fn actions(&self) -> AnalyzerActionIter<L>;
fn transformations(&self) -> AnalyzerTransformationIter<L>;
}
/// Simple implementation of [AnalyzerSignal] generating a [AnalyzerDiagnostic]
/// from a provided factory function. Optionally, this signal can be configured
/// to also emit a code action, by calling `.with_action` with a secondary
/// factory function for said action.
pub struct DiagnosticSignal<D, A, L, T, Tr> {
diagnostic: D,
action: A,
transformation: Tr,
_diag: PhantomData<(L, T)>,
}
impl<L: Language, D, T>
DiagnosticSignal<
D,
fn() -> Option<AnalyzerAction<L>>,
L,
T,
fn() -> Option<AnalyzerTransformation<L>>,
>
where
D: Fn() -> T,
Error: From<T>,
{
pub fn new(factory: D) -> Self {
Self {
diagnostic: factory,
action: || None,
transformation: || None,
_diag: PhantomData,
}
}
}
impl<L: Language, D, A, T, Tr> DiagnosticSignal<D, A, L, T, Tr> {
pub fn with_action<B>(self, factory: B) -> DiagnosticSignal<D, B, L, T, Tr>
where
B: Fn() -> Option<AnalyzerAction<L>>,
{
DiagnosticSignal {
diagnostic: self.diagnostic,
action: factory,
transformation: self.transformation,
_diag: PhantomData,
}
}
}
impl<L: Language, D, A, T, Tr> AnalyzerSignal<L> for DiagnosticSignal<D, A, L, T, Tr>
where
D: Fn() -> T,
Error: From<T>,
A: Fn() -> Option<AnalyzerAction<L>>,
Tr: Fn() -> Option<AnalyzerTransformation<L>>,
{
fn diagnostic(&self) -> Option<AnalyzerDiagnostic> {
let diag = (self.diagnostic)();
let error = Error::from(diag);
Some(AnalyzerDiagnostic::from_error(error))
}
fn actions(&self) -> AnalyzerActionIter<L> {
if let Some(action) = (self.action)() {
AnalyzerActionIter::new([action])
} else {
AnalyzerActionIter::new(vec![])
}
}
fn transformations(&self) -> AnalyzerTransformationIter<L> {
if let Some(transformation) = (self.transformation)() {
AnalyzerTransformationIter::new([transformation])
} else {
AnalyzerTransformationIter::new(vec![])
}
}
}
/// Code Action object returned by the analyzer, generated from a [crate::RuleAction]
/// with additional information about the rule injected by the analyzer
///
/// This struct can be converted into a [CodeSuggestion] and injected into
/// a diagnostic emitted by the same signal
#[derive(Debug, Clone)]
pub struct AnalyzerAction<L: Language> {
pub rule_name: Option<(&'static str, &'static str)>,
pub category: ActionCategory,
pub applicability: Applicability,
pub message: MarkupBuf,
pub mutation: BatchMutation<L>,
}
impl<L: Language> AnalyzerAction<L> {
pub fn is_suppression(&self) -> bool {
self.category.matches(SUPPRESSION_ACTION_CATEGORY)
}
}
pub struct AnalyzerActionIter<L: Language> {
analyzer_actions: IntoIter<AnalyzerAction<L>>,
}
impl<L: Language> Default for AnalyzerActionIter<L> {
fn default() -> Self {
Self {
analyzer_actions: vec![].into_iter(),
}
}
}
impl<L: Language> From<AnalyzerAction<L>> for CodeSuggestionAdvice<MarkupBuf> {
fn from(action: AnalyzerAction<L>) -> Self {
let (_, suggestion) = action.mutation.as_text_edits().unwrap_or_default();
CodeSuggestionAdvice {
applicability: action.applicability,
msg: action.message,
suggestion,
}
}
}
impl<L: Language> From<AnalyzerAction<L>> for CodeSuggestionItem {
fn from(action: AnalyzerAction<L>) -> Self {
let (range, suggestion) = action.mutation.as_text_edits().unwrap_or_default();
CodeSuggestionItem {
rule_name: action.rule_name,
category: action.category,
suggestion: CodeSuggestion {
span: range,
applicability: action.applicability,
msg: action.message,
suggestion,
labels: vec![],
},
}
}
}
impl<L: Language> AnalyzerActionIter<L> {
pub fn new<I>(actions: I) -> Self
where
I: IntoIterator<Item = AnalyzerAction<L>>,
I::IntoIter: ExactSizeIterator,
{
Self {
analyzer_actions: actions
.into_iter()
.collect::<Vec<AnalyzerAction<L>>>()
.into_iter(),
}
}
}
impl<L: Language> Iterator for AnalyzerActionIter<L> {
type Item = AnalyzerAction<L>;
fn next(&mut self) -> Option<Self::Item> {
self.analyzer_actions.next()
}
}
impl<L: Language> FusedIterator for AnalyzerActionIter<L> {}
impl<L: Language> ExactSizeIterator for AnalyzerActionIter<L> {
fn len(&self) -> usize {
self.analyzer_actions.len()
}
}
pub struct CodeSuggestionAdviceIter<L: Language> {
iter: IntoIter<AnalyzerAction<L>>,
}
impl<L: Language> Iterator for CodeSuggestionAdviceIter<L> {
type Item = CodeSuggestionAdvice<MarkupBuf>;
fn next(&mut self) -> Option<Self::Item> {
let action = self.iter.next()?;
Some(action.into())
}
}
impl<L: Language> FusedIterator for CodeSuggestionAdviceIter<L> {}
impl<L: Language> ExactSizeIterator for CodeSuggestionAdviceIter<L> {
fn len(&self) -> usize {
self.iter.len()
}
}
pub struct CodeActionIter<L: Language> {
iter: IntoIter<AnalyzerAction<L>>,
}
pub struct CodeSuggestionItem {
pub category: ActionCategory,
pub suggestion: CodeSuggestion,
pub rule_name: Option<(&'static str, &'static str)>,
}
impl<L: Language> Iterator for CodeActionIter<L> {
type Item = CodeSuggestionItem;
fn next(&mut self) -> Option<Self::Item> {
let action = self.iter.next()?;
Some(action.into())
}
}
impl<L: Language> FusedIterator for CodeActionIter<L> {}
impl<L: Language> ExactSizeIterator for CodeActionIter<L> {
fn len(&self) -> usize {
self.iter.len()
}
}
impl<L: Language> AnalyzerActionIter<L> {
/// Returns an iterator that yields [CodeSuggestionAdvice]
pub fn into_code_suggestion_advices(self) -> CodeSuggestionAdviceIter<L> {
CodeSuggestionAdviceIter {
iter: self.analyzer_actions,
}
}
/// Returns an iterator that yields [CodeAction]
pub fn into_code_action_iter(self) -> CodeActionIter<L> {
CodeActionIter {
iter: self.analyzer_actions,
}
}
}
pub struct AnalyzerTransformationIter<L: Language> {
analyzer_transformations: IntoIter<AnalyzerTransformation<L>>,
}
impl<L: Language> Default for AnalyzerTransformationIter<L> {
fn default() -> Self {
Self {
analyzer_transformations: vec![].into_iter(),
}
}
}
impl<L: Language> AnalyzerTransformationIter<L> {
pub fn new<I>(transformations: I) -> Self
where
I: IntoIterator<Item = AnalyzerTransformation<L>>,
I::IntoIter: ExactSizeIterator,
{
Self {
analyzer_transformations: transformations
.into_iter()
.collect::<Vec<AnalyzerTransformation<L>>>()
.into_iter(),
}
}
}
impl<L: Language> Iterator for AnalyzerTransformationIter<L> {
type Item = AnalyzerTransformation<L>;
fn next(&mut self) -> Option<Self::Item> {
self.analyzer_transformations.next()
}
}
impl<L: Language> FusedIterator for AnalyzerTransformationIter<L> {}
impl<L: Language> ExactSizeIterator for AnalyzerTransformationIter<L> {
fn len(&self) -> usize {
self.analyzer_transformations.len()
}
}
#[derive(Debug, Clone)]
pub struct AnalyzerTransformation<L: Language> {
pub mutation: BatchMutation<L>,
}
/// Analyzer-internal implementation of [AnalyzerSignal] for a specific [Rule](crate::registry::Rule)
pub(crate) struct RuleSignal<'phase, R: Rule> {
root: &'phase RuleRoot<R>,
query_result: <<R as Rule>::Query as Queryable>::Output,
state: R::State,
services: &'phase ServiceBag,
/// An optional action to suppress the rule.
apply_suppression_comment: SuppressionCommentEmitter<RuleLanguage<R>>,
/// A list of strings that are considered "globals" inside the analyzer
options: &'phase AnalyzerOptions,
}
impl<'phase, R> RuleSignal<'phase, R>
where
R: Rule + 'static,
{
pub(crate) fn new(
root: &'phase RuleRoot<R>,
query_result: <<R as Rule>::Query as Queryable>::Output,
state: R::State,
services: &'phase ServiceBag,
apply_suppression_comment: SuppressionCommentEmitter<
<<R as Rule>::Query as Queryable>::Language,
>,
options: &'phase AnalyzerOptions,
) -> Self {
Self {
root,
query_result,
state,
services,
apply_suppression_comment,
options,
}
}
}
impl<'bag, R> AnalyzerSignal<RuleLanguage<R>> for RuleSignal<'bag, R>
where
R: Rule + 'static,
<R as Rule>::Options: Default,
{
fn diagnostic(&self) -> Option<AnalyzerDiagnostic> {
let globals = self.options.globals();
let options = self.options.rule_options::<R>().unwrap_or_default();
let ctx = RuleContext::new(
&self.query_result,
self.root,
self.services,
&globals,
&self.options.file_path,
&options,
)
.ok()?;
R::diagnostic(&ctx, &self.state).map(AnalyzerDiagnostic::from)
}
fn actions(&self) -> AnalyzerActionIter<RuleLanguage<R>> {
let globals = self.options.globals();
let options = self.options.rule_options::<R>().unwrap_or_default();
let ctx = RuleContext::new(
&self.query_result,
self.root,
self.services,
&globals,
&self.options.file_path,
&options,
)
.ok();
if let Some(ctx) = ctx {
let mut actions = Vec::new();
if let Some(action) = R::action(&ctx, &self.state) {
actions.push(AnalyzerAction {
rule_name: Some((<R::Group as RuleGroup>::NAME, R::METADATA.name)),
category: action.category,
applicability: action.applicability,
mutation: action.mutation,
message: action.message,
});
};
if let Some(text_range) = R::text_range(&ctx, &self.state) {
if let Some(suppression_action) =
R::suppress(&ctx, &text_range, self.apply_suppression_comment)
{
let action = AnalyzerAction {
rule_name: Some((<R::Group as RuleGroup>::NAME, R::METADATA.name)),
category: ActionCategory::Other(Cow::Borrowed(SUPPRESSION_ACTION_CATEGORY)),
applicability: Applicability::Always,
mutation: suppression_action.mutation,
message: suppression_action.message,
};
actions.push(action);
}
}
AnalyzerActionIter::new(actions)
} else {
AnalyzerActionIter::new(vec![])
}
}
fn transformations(&self) -> AnalyzerTransformationIter<RuleLanguage<R>> {
let globals = self.options.globals();
let options = self.options.rule_options::<R>().unwrap_or_default();
let ctx = RuleContext::new(
&self.query_result,
self.root,
self.services,
&globals,
&self.options.file_path,
&options,
)
.ok();
if let Some(ctx) = ctx {
let mut transformations = Vec::new();
let mutation = R::transform(&ctx, &self.state);
if let Some(mutation) = mutation {
let transformation = AnalyzerTransformation { mutation };
transformations.push(transformation)
}
AnalyzerTransformationIter::new(transformations)
} else {
AnalyzerTransformationIter::new(vec![])
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/binding_ext.rs | crates/rome_js_syntax/src/binding_ext.rs | use crate::{
JsArrowFunctionExpression, JsBogusNamedImportSpecifier, JsBogusParameter, JsCatchDeclaration,
JsClassDeclaration, JsClassExportDefaultDeclaration, JsClassExpression,
JsConstructorClassMember, JsConstructorParameterList, JsConstructorParameters,
JsDefaultImportSpecifier, JsFormalParameter, JsFunctionDeclaration,
JsFunctionExportDefaultDeclaration, JsFunctionExpression, JsIdentifierBinding,
JsImportDefaultClause, JsImportNamespaceClause, JsMethodClassMember, JsMethodObjectMember,
JsNamedImportSpecifier, JsNamespaceImportSpecifier, JsParameterList, JsParameters,
JsRestParameter, JsSetterClassMember, JsSetterObjectMember, JsShorthandNamedImportSpecifier,
JsSyntaxKind, JsSyntaxNode, JsSyntaxToken, JsVariableDeclarator, TsCallSignatureTypeMember,
TsConstructSignatureTypeMember, TsConstructorSignatureClassMember, TsConstructorType,
TsDeclareFunctionDeclaration, TsDeclareFunctionExportDefaultDeclaration, TsEnumDeclaration,
TsFunctionType, TsIdentifierBinding, TsImportEqualsDeclaration, TsIndexSignatureClassMember,
TsIndexSignatureParameter, TsInterfaceDeclaration, TsMethodSignatureClassMember,
TsMethodSignatureTypeMember, TsModuleDeclaration, TsPropertyParameter,
TsSetterSignatureClassMember, TsSetterSignatureTypeMember, TsTypeAliasDeclaration,
TsTypeParameterName,
};
use rome_rowan::{declare_node_union, AstNode, SyntaxResult};
declare_node_union! {
pub AnyJsBindingDeclaration =
// variable
JsVariableDeclarator
// parameters
| JsFormalParameter | JsRestParameter | JsBogusParameter
| TsIndexSignatureParameter | TsPropertyParameter
// functions
| JsFunctionDeclaration | JsFunctionExpression
| TsDeclareFunctionDeclaration
// classes, objects, interface, type, enum, module
| JsClassDeclaration | JsClassExpression
| TsInterfaceDeclaration | TsTypeAliasDeclaration | TsEnumDeclaration | TsModuleDeclaration
// import
| JsImportDefaultClause | JsImportNamespaceClause | JsShorthandNamedImportSpecifier
| JsNamedImportSpecifier | JsBogusNamedImportSpecifier | JsDefaultImportSpecifier
| JsNamespaceImportSpecifier
| TsImportEqualsDeclaration
// export
| JsClassExportDefaultDeclaration | JsFunctionExportDefaultDeclaration
| TsDeclareFunctionExportDefaultDeclaration
// try/catch
| JsCatchDeclaration
}
impl AnyJsBindingDeclaration {
/// Returns `true` if `self` and `other` are mergeable declarations.
///
/// See also: <https://www.typescriptlang.org/docs/handbook/declaration-merging.html>
///
/// ## Examples
///
/// A namespace can merge with a class, an enum.
/// However, an enum cannot merge with a class.
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::{binding_ext::AnyJsBindingDeclaration, T};
///
/// let enum_id = make::js_identifier_binding(make::ident("Order"));
/// let enum_decl: AnyJsBindingDeclaration = make::ts_enum_declaration(
/// make::token(T![enum]),
/// enum_id.into(),
/// make::token(T!['{']),
/// make::ts_enum_member_list(
/// [],
/// Some(make::token(T![;])),
/// ),
/// make::token(T!['}']),
/// ).build().into();
///
/// let namespace_id = make::ts_identifier_binding(make::ident("Order"));
/// let namespace_decl: AnyJsBindingDeclaration = make::ts_module_declaration(
/// make::token(T![namespace]),
/// namespace_id.into(),
/// make::ts_module_block(
/// make::token(T!['{']),
/// make::js_module_item_list([]),
/// make::token(T!['}']),
/// ),
/// ).into();
///
/// let class_id = make::js_identifier_binding(make::ident("Order"));
/// let class_decl: AnyJsBindingDeclaration = make::js_class_declaration(
/// make::js_decorator_list([]),
/// make::token(T![class]),
/// class_id.into(),
/// make::token(T!['{']),
/// make::js_class_member_list([]),
/// make::token(T!['}']),
/// ).build().into();
///
/// assert!(enum_decl.is_mergeable(&namespace_decl));
/// assert!(namespace_decl.is_mergeable(&enum_decl));
///
/// assert!(class_decl.is_mergeable(&namespace_decl));
/// assert!(namespace_decl.is_mergeable(&class_decl));
///
/// assert!(!class_decl.is_mergeable(&enum_decl));
/// assert!(!enum_decl.is_mergeable(&class_decl));
/// ```
pub const fn is_mergeable(&self, other: &AnyJsBindingDeclaration) -> bool {
Self::can_merge(self, other) || Self::can_merge(other, self)
}
/// Please use `is_mergeable`.
/// `can_merge` is sensible to the order of arguments.
const fn can_merge(a: &AnyJsBindingDeclaration, b: &AnyJsBindingDeclaration) -> bool {
match (a, b) {
(
AnyJsBindingDeclaration::TsDeclareFunctionDeclaration(_),
AnyJsBindingDeclaration::JsFunctionDeclaration(_)
| AnyJsBindingDeclaration::TsDeclareFunctionDeclaration(_),
) => true,
(
AnyJsBindingDeclaration::TsEnumDeclaration(_),
AnyJsBindingDeclaration::TsEnumDeclaration(_),
) => true,
(
AnyJsBindingDeclaration::TsTypeAliasDeclaration(_),
AnyJsBindingDeclaration::JsFunctionDeclaration(_)
| AnyJsBindingDeclaration::JsVariableDeclarator(_)
| AnyJsBindingDeclaration::TsModuleDeclaration(_),
) => true,
(
AnyJsBindingDeclaration::TsInterfaceDeclaration(_),
AnyJsBindingDeclaration::JsClassDeclaration(_)
| AnyJsBindingDeclaration::JsFunctionDeclaration(_)
| AnyJsBindingDeclaration::JsVariableDeclarator(_)
| AnyJsBindingDeclaration::TsDeclareFunctionDeclaration(_)
| AnyJsBindingDeclaration::TsInterfaceDeclaration(_)
| AnyJsBindingDeclaration::TsModuleDeclaration(_),
) => true,
(
AnyJsBindingDeclaration::TsModuleDeclaration(_),
AnyJsBindingDeclaration::JsClassDeclaration(_)
| AnyJsBindingDeclaration::JsFunctionDeclaration(_)
| AnyJsBindingDeclaration::JsVariableDeclarator(_)
| AnyJsBindingDeclaration::TsDeclareFunctionDeclaration(_)
| AnyJsBindingDeclaration::TsEnumDeclaration(_)
| AnyJsBindingDeclaration::TsInterfaceDeclaration(_)
| AnyJsBindingDeclaration::TsModuleDeclaration(_),
) => true,
(_, _) => false,
}
}
/// Returns `true` if `self` is a formal parameter, a rest parameter,
/// a property parameter, or a bogus parameter.
pub const fn is_parameter_like(&self) -> bool {
matches!(
self,
AnyJsBindingDeclaration::JsFormalParameter(_)
| AnyJsBindingDeclaration::JsRestParameter(_)
| AnyJsBindingDeclaration::JsBogusParameter(_)
| AnyJsBindingDeclaration::TsPropertyParameter(_)
)
}
}
declare_node_union! {
pub AnyJsIdentifierBinding = JsIdentifierBinding | TsIdentifierBinding | TsTypeParameterName
}
fn declaration(node: &JsSyntaxNode) -> Option<AnyJsBindingDeclaration> {
use JsSyntaxKind::*;
let parent = node.parent()?;
let possible_declarator = parent.ancestors().find(|x| {
!matches!(
x.kind(),
JS_BINDING_PATTERN_WITH_DEFAULT
| JS_OBJECT_BINDING_PATTERN
| JS_OBJECT_BINDING_PATTERN_REST
| JS_OBJECT_BINDING_PATTERN_PROPERTY
| JS_OBJECT_BINDING_PATTERN_PROPERTY_LIST
| JS_OBJECT_BINDING_PATTERN_SHORTHAND_PROPERTY
| JS_ARRAY_BINDING_PATTERN
| JS_ARRAY_BINDING_PATTERN_ELEMENT_LIST
| JS_ARRAY_BINDING_PATTERN_REST_ELEMENT
)
})?;
match AnyJsBindingDeclaration::cast(possible_declarator)? {
AnyJsBindingDeclaration::JsFormalParameter(parameter) => {
match parameter.parent::<TsPropertyParameter>() {
Some(parameter) => Some(AnyJsBindingDeclaration::TsPropertyParameter(parameter)),
None => Some(AnyJsBindingDeclaration::JsFormalParameter(parameter)),
}
}
declaration => Some(declaration),
}
}
fn is_under_pattern_binding(node: &JsSyntaxNode) -> Option<bool> {
use JsSyntaxKind::*;
Some(matches!(
node.parent()?.kind(),
JS_BINDING_PATTERN_WITH_DEFAULT
| JS_OBJECT_BINDING_PATTERN
| JS_OBJECT_BINDING_PATTERN_REST
| JS_OBJECT_BINDING_PATTERN_PROPERTY
| JS_OBJECT_BINDING_PATTERN_PROPERTY_LIST
| JS_OBJECT_BINDING_PATTERN_SHORTHAND_PROPERTY
| JS_ARRAY_BINDING_PATTERN
| JS_ARRAY_BINDING_PATTERN_ELEMENT_LIST
| JS_ARRAY_BINDING_PATTERN_REST_ELEMENT
))
}
fn is_under_array_pattern_binding(node: &JsSyntaxNode) -> Option<bool> {
use JsSyntaxKind::*;
let parent = node.parent()?;
match parent.kind() {
JS_ARRAY_BINDING_PATTERN
| JS_ARRAY_BINDING_PATTERN_ELEMENT_LIST
| JS_ARRAY_BINDING_PATTERN_REST_ELEMENT => Some(true),
JS_BINDING_PATTERN_WITH_DEFAULT => is_under_array_pattern_binding(&parent),
_ => Some(false),
}
}
fn is_under_object_pattern_binding(node: &JsSyntaxNode) -> Option<bool> {
use JsSyntaxKind::*;
let parent = node.parent()?;
match parent.kind() {
JS_OBJECT_BINDING_PATTERN
| JS_OBJECT_BINDING_PATTERN_REST
| JS_OBJECT_BINDING_PATTERN_PROPERTY
| JS_OBJECT_BINDING_PATTERN_PROPERTY_LIST
| JS_OBJECT_BINDING_PATTERN_SHORTHAND_PROPERTY => Some(true),
JS_BINDING_PATTERN_WITH_DEFAULT => is_under_object_pattern_binding(&parent),
_ => Some(false),
}
}
impl AnyJsIdentifierBinding {
pub fn name_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsIdentifierBinding::JsIdentifierBinding(binding) => binding.name_token(),
AnyJsIdentifierBinding::TsIdentifierBinding(binding) => binding.name_token(),
AnyJsIdentifierBinding::TsTypeParameterName(binding) => binding.ident_token(),
}
}
pub fn declaration(&self) -> Option<AnyJsBindingDeclaration> {
let node = match self {
AnyJsIdentifierBinding::JsIdentifierBinding(binding) => &binding.syntax,
AnyJsIdentifierBinding::TsIdentifierBinding(binding) => &binding.syntax,
AnyJsIdentifierBinding::TsTypeParameterName(binding) => &binding.syntax,
};
declaration(node)
}
pub fn is_under_pattern_binding(&self) -> Option<bool> {
is_under_pattern_binding(self.syntax())
}
pub fn is_under_array_pattern_binding(&self) -> Option<bool> {
is_under_array_pattern_binding(self.syntax())
}
pub fn is_under_object_pattern_binding(&self) -> Option<bool> {
is_under_object_pattern_binding(self.syntax())
}
pub fn with_name_token(self, name_token: JsSyntaxToken) -> AnyJsIdentifierBinding {
match self {
AnyJsIdentifierBinding::JsIdentifierBinding(binding) => {
AnyJsIdentifierBinding::JsIdentifierBinding(binding.with_name_token(name_token))
}
AnyJsIdentifierBinding::TsIdentifierBinding(binding) => {
AnyJsIdentifierBinding::TsIdentifierBinding(binding.with_name_token(name_token))
}
AnyJsIdentifierBinding::TsTypeParameterName(binding) => {
AnyJsIdentifierBinding::TsTypeParameterName(binding.with_ident_token(name_token))
}
}
}
}
impl JsIdentifierBinding {
/// Navigate upward until the declaration of this binding bypassing all nodes
/// related to pattern binding.
pub fn declaration(&self) -> Option<AnyJsBindingDeclaration> {
declaration(&self.syntax)
}
pub fn is_under_pattern_binding(&self) -> Option<bool> {
is_under_pattern_binding(self.syntax())
}
pub fn is_under_array_pattern_binding(&self) -> Option<bool> {
is_under_array_pattern_binding(self.syntax())
}
pub fn is_under_object_pattern_binding(&self) -> Option<bool> {
is_under_object_pattern_binding(self.syntax())
}
}
impl TsIdentifierBinding {
pub fn declaration(&self) -> Option<AnyJsBindingDeclaration> {
declaration(&self.syntax)
}
pub fn is_under_pattern_binding(&self) -> Option<bool> {
is_under_pattern_binding(self.syntax())
}
pub fn is_under_array_pattern_binding(&self) -> Option<bool> {
is_under_array_pattern_binding(self.syntax())
}
pub fn is_under_object_pattern_binding(&self) -> Option<bool> {
is_under_object_pattern_binding(self.syntax())
}
}
declare_node_union! {
pub JsAnyParameterParentFunction =
JsFunctionDeclaration
| JsFunctionExpression
| JsArrowFunctionExpression
| JsFunctionExportDefaultDeclaration
| JsConstructorClassMember
| JsMethodClassMember
| JsSetterClassMember
| JsMethodObjectMember
| JsSetterObjectMember
| TsFunctionType
| TsConstructorType
| TsDeclareFunctionDeclaration
| TsDeclareFunctionExportDefaultDeclaration
| TsConstructorSignatureClassMember
| TsMethodSignatureClassMember
| TsSetterSignatureClassMember
| TsIndexSignatureClassMember
| TsConstructSignatureTypeMember
| TsMethodSignatureTypeMember
| TsSetterSignatureTypeMember
| TsCallSignatureTypeMember
}
fn parent_function(node: &JsSyntaxNode) -> Option<JsAnyParameterParentFunction> {
let parent = node.parent()?;
match parent.kind() {
JsSyntaxKind::JS_PARAMETER_LIST => {
// SAFETY: kind check above
let parameters = JsParameterList::unwrap_cast(parent).parent::<JsParameters>()?;
let parent = parameters.syntax.parent()?;
JsAnyParameterParentFunction::cast(parent)
}
JsSyntaxKind::JS_CONSTRUCTOR_PARAMETER_LIST => {
// SAFETY: kind check above
let parameters = JsConstructorParameterList::unwrap_cast(parent)
.parent::<JsConstructorParameters>()?;
let parent = parameters.syntax().parent()?;
JsAnyParameterParentFunction::cast(parent)
}
_ => JsAnyParameterParentFunction::cast(parent),
}
}
impl JsFormalParameter {
pub fn parent_function(&self) -> Option<JsAnyParameterParentFunction> {
parent_function(&self.syntax)
}
}
impl JsRestParameter {
pub fn parent_function(&self) -> Option<JsAnyParameterParentFunction> {
parent_function(&self.syntax)
}
}
impl TsPropertyParameter {
pub fn parent_function(&self) -> Option<JsAnyParameterParentFunction> {
parent_function(&self.syntax)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/import_ext.rs | crates/rome_js_syntax/src/import_ext.rs | use crate::{inner_string_text, AnyJsImportClause, JsImport, JsModuleSource};
use rome_rowan::{SyntaxResult, TokenText};
impl JsImport {
/// It checks if the source of an import against the string `source_to_check`
///
/// ## Examples
///
/// ```
/// use rome_js_factory::make::{js_reference_identifier, ident, js_module_source, js_import_default_clause, token, js_identifier_binding, js_import};
/// use rome_js_syntax::{AnyJsBinding, AnyJsImportClause, T};
/// let source = js_module_source(ident("react"));
/// let binding = js_identifier_binding(ident("React"));
/// let clause = js_import_default_clause(AnyJsBinding::JsIdentifierBinding(binding), token(T![from]), source).build();
/// let import = js_import(token(T![import]), AnyJsImportClause::JsImportDefaultClause(clause)).build();
/// assert_eq!(import.source_is("react"), Ok(true));
/// assert_eq!(import.source_is("React"), Ok(false));
/// ```
pub fn source_is(&self, source_to_check: &str) -> SyntaxResult<bool> {
let clause = self.import_clause()?;
let source = match clause {
AnyJsImportClause::JsImportBareClause(node) => node.source(),
AnyJsImportClause::JsImportDefaultClause(node) => node.source(),
AnyJsImportClause::JsImportNamedClause(node) => node.source(),
AnyJsImportClause::JsImportNamespaceClause(node) => node.source(),
}?;
Ok(source.inner_string_text()?.text() == source_to_check)
}
}
impl JsModuleSource {
/// Get the inner text of a string not including the quotes
/// ## Examples
///
/// ```
/// use rome_js_factory::make::{ident, js_module_source};
/// use rome_js_syntax::{AnyJsBinding, AnyJsImportClause, T};
/// use rome_rowan::TriviaPieceKind;
/// let source = js_module_source(ident("react").with_leading_trivia(vec![(TriviaPieceKind::Whitespace, " ")]));
/// let text = source.inner_string_text().unwrap();
/// assert_eq!(text.text(), "react");
/// ```
pub fn inner_string_text(&self) -> SyntaxResult<TokenText> {
Ok(inner_string_text(&self.value_token()?))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/lib.rs | crates/rome_js_syntax/src/lib.rs | //! A crate for generated Syntax node definitions and utility macros.
//! Both rome_js_lexer and rome_js_parser rely on these definitions, therefore
//! they are wrapped in this crate to prevent cyclic dependencies
#[macro_use]
mod generated;
pub mod binding_ext;
pub mod directive_ext;
pub mod expr_ext;
pub mod file_source;
pub mod function_ext;
pub mod identifier_ext;
pub mod import_ext;
pub mod jsx_ext;
pub mod modifier_ext;
pub mod numbers;
pub mod parameter_ext;
pub mod static_value;
pub mod stmt_ext;
pub mod suppression;
mod syntax_node;
pub mod type_ext;
mod union_ext;
pub use self::generated::*;
pub use expr_ext::*;
pub use file_source::*;
pub use function_ext::*;
pub use identifier_ext::*;
pub use modifier_ext::*;
pub use rome_rowan::{
SyntaxNodeText, TextLen, TextRange, TextSize, TokenAtOffset, TokenText, TriviaPieceKind,
WalkEvent,
};
pub use stmt_ext::*;
pub use syntax_node::*;
pub use type_ext::*;
use crate::JsSyntaxKind::*;
use rome_rowan::{AstNode, RawSyntaxKind};
impl From<u16> for JsSyntaxKind {
fn from(d: u16) -> JsSyntaxKind {
assert!(d <= (JsSyntaxKind::__LAST as u16));
unsafe { std::mem::transmute::<u16, JsSyntaxKind>(d) }
}
}
impl From<JsSyntaxKind> for u16 {
fn from(k: JsSyntaxKind) -> u16 {
k as u16
}
}
impl JsSyntaxKind {
pub fn is_trivia(self) -> bool {
matches!(
self,
JsSyntaxKind::NEWLINE
| JsSyntaxKind::WHITESPACE
| JsSyntaxKind::COMMENT
| JsSyntaxKind::MULTILINE_COMMENT
)
}
/// Returns `true` for any contextual (await) or non-contextual keyword
#[inline]
pub const fn is_keyword(self) -> bool {
(self as u16) <= (JsSyntaxKind::USING_KW as u16)
&& (self as u16) >= (JsSyntaxKind::BREAK_KW as u16)
}
/// Returns `true` for contextual keywords (excluding strict mode contextual keywords)
#[inline]
pub const fn is_contextual_keyword(self) -> bool {
(self as u16) >= (JsSyntaxKind::ABSTRACT_KW as u16)
&& (self as u16) <= (JsSyntaxKind::USING_KW as u16)
}
/// Returns true for all non-contextual keywords (includes future reserved keywords)
#[inline]
pub const fn is_non_contextual_keyword(self) -> bool {
self.is_keyword() && !self.is_contextual_keyword()
}
#[inline]
pub const fn is_future_reserved_keyword(self) -> bool {
(self as u16) >= (JsSyntaxKind::IMPLEMENTS_KW as u16)
&& (self as u16) <= (JsSyntaxKind::YIELD_KW as u16)
}
}
impl rome_rowan::SyntaxKind for JsSyntaxKind {
const TOMBSTONE: Self = TOMBSTONE;
const EOF: Self = EOF;
fn is_bogus(&self) -> bool {
matches!(
self,
JS_BOGUS
| JS_BOGUS_STATEMENT
| JS_BOGUS_PARAMETER
| JS_BOGUS_BINDING
| JS_BOGUS_MEMBER
| JS_BOGUS_EXPRESSION
| JS_BOGUS_IMPORT_ASSERTION_ENTRY
| JS_BOGUS_NAMED_IMPORT_SPECIFIER
| JS_BOGUS_ASSIGNMENT
| TS_BOGUS_TYPE
)
}
fn to_bogus(&self) -> JsSyntaxKind {
match self {
kind if AnyJsModuleItem::can_cast(*kind) => JS_BOGUS_STATEMENT,
kind if AnyJsExpression::can_cast(*kind) => JS_BOGUS_EXPRESSION,
kind if AnyJsBinding::can_cast(*kind) => JS_BOGUS_BINDING,
kind if AnyJsClassMember::can_cast(*kind) || AnyJsObjectMember::can_cast(*kind) => {
JS_BOGUS_MEMBER
}
kind if AnyJsAssignment::can_cast(*kind) => JS_BOGUS_ASSIGNMENT,
kind if AnyJsNamedImportSpecifier::can_cast(*kind) => JS_BOGUS_NAMED_IMPORT_SPECIFIER,
kind if AnyJsImportAssertionEntry::can_cast(*kind) => JS_BOGUS_IMPORT_ASSERTION_ENTRY,
kind if AnyJsParameter::can_cast(*kind) => JS_BOGUS_PARAMETER,
kind if AnyTsType::can_cast(*kind) => TS_BOGUS_TYPE,
_ => JS_BOGUS,
}
}
#[inline]
fn to_raw(&self) -> RawSyntaxKind {
RawSyntaxKind(*self as u16)
}
#[inline]
fn from_raw(raw: RawSyntaxKind) -> Self {
Self::from(raw.0)
}
fn is_root(&self) -> bool {
AnyJsRoot::can_cast(*self)
}
fn is_list(&self) -> bool {
JsSyntaxKind::is_list(*self)
}
fn to_string(&self) -> Option<&'static str> {
JsSyntaxKind::to_string(self)
}
}
impl TryFrom<JsSyntaxKind> for TriviaPieceKind {
type Error = ();
fn try_from(value: JsSyntaxKind) -> Result<Self, Self::Error> {
if value.is_trivia() {
match value {
JsSyntaxKind::NEWLINE => Ok(TriviaPieceKind::Newline),
JsSyntaxKind::WHITESPACE => Ok(TriviaPieceKind::Whitespace),
JsSyntaxKind::COMMENT => Ok(TriviaPieceKind::SingleLineComment),
JsSyntaxKind::MULTILINE_COMMENT => Ok(TriviaPieceKind::MultiLineComment),
_ => unreachable!("Not Trivia"),
}
} else {
Err(())
}
}
}
/// See: [MDN Operator precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#table)
#[allow(dead_code)]
#[derive(Debug, Eq, Ord, PartialOrd, PartialEq, Copy, Clone, Hash)]
pub enum OperatorPrecedence {
Comma = 0,
Yield = 1,
Assignment = 2,
Conditional = 3,
Coalesce = 4,
LogicalOr = 5,
LogicalAnd = 6,
BitwiseOr = 7,
BitwiseXor = 8,
BitwiseAnd = 9,
Equality = 10,
Relational = 11,
Shift = 12,
Additive = 13,
Multiplicative = 14,
Exponential = 15,
Unary = 16,
Update = 17,
// `new` without arguments list
NewWithoutArguments = 18,
LeftHandSide = 19,
Member = 20,
Primary = 21,
Group = 22,
}
impl OperatorPrecedence {
/// Returns the operator with the lowest precedence
pub fn lowest() -> Self {
OperatorPrecedence::Comma
}
/// Returns the operator with the highest precedence
#[allow(dead_code)]
pub fn highest() -> Self {
OperatorPrecedence::Primary
}
/// Returns `true` if this operator has right to left associativity
pub fn is_right_to_left(&self) -> bool {
matches!(
self,
OperatorPrecedence::Yield
| OperatorPrecedence::Assignment
| OperatorPrecedence::Conditional
| OperatorPrecedence::Exponential
| OperatorPrecedence::Update
)
}
/// Returns the precedence for a binary operator token or [None] if the token isn't a binary operator
pub fn try_from_binary_operator(kind: JsSyntaxKind) -> Option<OperatorPrecedence> {
Some(match kind {
T![??] => OperatorPrecedence::Coalesce,
T![||] => OperatorPrecedence::LogicalOr,
T![&&] => OperatorPrecedence::LogicalAnd,
T![|] => OperatorPrecedence::BitwiseOr,
T![^] => OperatorPrecedence::BitwiseXor,
T![&] => OperatorPrecedence::BitwiseAnd,
T![==] | T![!=] | T![===] | T![!==] => OperatorPrecedence::Equality,
T![<] | T![>] | T![<=] | T![>=] | T![instanceof] | T![in] | T![as] | T![satisfies] => {
OperatorPrecedence::Relational
}
T![<<] | T![>>] | T![>>>] => OperatorPrecedence::Shift,
T![+] | T![-] => OperatorPrecedence::Additive,
T![*] | T![/] | T![%] => OperatorPrecedence::Multiplicative,
T![**] => OperatorPrecedence::Exponential,
_ => return None,
})
}
pub const fn is_bitwise(&self) -> bool {
matches!(
self,
OperatorPrecedence::BitwiseAnd
| OperatorPrecedence::BitwiseOr
| OperatorPrecedence::BitwiseXor
)
}
pub const fn is_shift(&self) -> bool {
matches!(self, OperatorPrecedence::Shift)
}
pub const fn is_additive(&self) -> bool {
matches!(self, OperatorPrecedence::Additive)
}
pub const fn is_equality(&self) -> bool {
matches!(self, OperatorPrecedence::Equality)
}
pub const fn is_multiplicative(&self) -> bool {
matches!(self, OperatorPrecedence::Multiplicative)
}
pub const fn is_exponential(&self) -> bool {
matches!(self, OperatorPrecedence::Exponential)
}
}
/// Similar to [JsSyntaxToken::text_trimmed()], but removes the quotes of string literals.
///
/// ## Examples
///
/// ```
/// use rome_js_syntax::{JsSyntaxKind, JsSyntaxToken, inner_string_text};
///
/// let a = JsSyntaxToken::new_detached(JsSyntaxKind::JS_STRING_LITERAL, "'inner_string_text'", [], []);
/// let b = JsSyntaxToken::new_detached(JsSyntaxKind::JS_STRING_LITERAL, "\"inner_string_text\"", [], []);
/// assert_eq!(inner_string_text(&a), inner_string_text(&b));
///
/// let a = JsSyntaxToken::new_detached(JsSyntaxKind::LET_KW, "let", [], []);
/// let b = JsSyntaxToken::new_detached(JsSyntaxKind::LET_KW, "let", [], []);
/// assert_eq!(inner_string_text(&a), inner_string_text(&b));
///
/// let a = JsSyntaxToken::new_detached(JsSyntaxKind::LET_KW, "let", [], []);
/// let b = JsSyntaxToken::new_detached(JsSyntaxKind::CONST_KW, "const", [], []);
/// assert!(inner_string_text(&a) != inner_string_text(&b));
/// ```
pub fn inner_string_text(token: &JsSyntaxToken) -> TokenText {
let mut text = token.token_text_trimmed();
if matches!(
token.kind(),
JsSyntaxKind::JS_STRING_LITERAL | JsSyntaxKind::JSX_STRING_LITERAL
) {
// remove string delimiters
// SAFETY: string literal token have a delimiters at the start and the end of the string
let range = TextRange::new(1.into(), text.len() - TextSize::from(1));
text = text.slice(range);
}
text
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/function_ext.rs | crates/rome_js_syntax/src/function_ext.rs | use crate::{
AnyJsFunction, AnyJsFunctionBody, JsMethodClassMember, JsMethodObjectMember, JsStatementList,
JsSyntaxToken,
};
use rome_rowan::{declare_node_union, AstNode, SyntaxResult, TextRange};
declare_node_union! {
pub AnyFunctionLike = AnyJsFunction | JsMethodObjectMember | JsMethodClassMember
}
impl AnyFunctionLike {
pub fn body(&self) -> SyntaxResult<AnyJsFunctionBody> {
match self {
AnyFunctionLike::AnyJsFunction(js_function) => js_function.body(),
AnyFunctionLike::JsMethodObjectMember(js_object_method) => js_object_method
.body()
.map(AnyJsFunctionBody::JsFunctionBody),
AnyFunctionLike::JsMethodClassMember(js_class_method) => js_class_method
.body()
.map(AnyJsFunctionBody::JsFunctionBody),
}
}
pub fn fat_arrow_token(&self) -> Option<JsSyntaxToken> {
match self {
AnyFunctionLike::AnyJsFunction(any_js_function) => {
if let Some(arrow_expression) = any_js_function.as_js_arrow_function_expression() {
arrow_expression.fat_arrow_token().ok()
} else {
None
}
}
AnyFunctionLike::JsMethodClassMember(_) | AnyFunctionLike::JsMethodObjectMember(_) => {
None
}
}
}
pub fn function_token(&self) -> Option<JsSyntaxToken> {
match self {
AnyFunctionLike::AnyJsFunction(any_js_function) => {
any_js_function.function_token().ok().flatten()
}
AnyFunctionLike::JsMethodClassMember(_) | AnyFunctionLike::JsMethodObjectMember(_) => {
None
}
}
}
pub fn is_generator(&self) -> bool {
match self {
AnyFunctionLike::AnyJsFunction(any_js_function) => any_js_function.is_generator(),
AnyFunctionLike::JsMethodClassMember(method_class_member) => {
method_class_member.star_token().is_some()
}
AnyFunctionLike::JsMethodObjectMember(method_obj_member) => {
method_obj_member.star_token().is_some()
}
}
}
pub fn name_range(&self) -> Option<TextRange> {
match self {
AnyFunctionLike::AnyJsFunction(js_function) => {
js_function.id().ok().flatten().map(|id| id.range())
}
AnyFunctionLike::JsMethodObjectMember(js_object_method) => {
js_object_method.name().ok().map(|name| name.range())
}
AnyFunctionLike::JsMethodClassMember(js_class_method) => {
js_class_method.name().ok().map(|name| name.range())
}
}
}
pub fn statements(&self) -> Option<JsStatementList> {
Some(match self {
AnyFunctionLike::AnyJsFunction(any_js_function) => any_js_function
.body()
.ok()?
.as_js_function_body()?
.statements(),
AnyFunctionLike::JsMethodClassMember(method_class_member) => {
method_class_member.body().ok()?.statements()
}
AnyFunctionLike::JsMethodObjectMember(method_obj_member) => {
method_obj_member.body().ok()?.statements()
}
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/suppression.rs | crates/rome_js_syntax/src/suppression.rs | use rome_diagnostics::{Category, Diagnostic};
use rome_rowan::{TextRange, TextSize};
/// Single instance of a suppression comment, with the following syntax:
///
/// `// rome-ignore { <category> { (<value>) }? }+: <reason>`
///
/// The category broadly describes what feature is being suppressed (formatting,
/// linting, ...) with the value being and optional, category-specific name of
/// a specific element to disable (for instance a specific lint name). A single
/// suppression may specify one or more categories + values, for instance to
/// disable multiple lints at once
///
/// A suppression must specify a reason: this part has no semantic meaning but
/// is required to document why a particular feature is being disable for this
/// line (lint false-positive, specific formatting requirements, ...)
#[derive(Debug, PartialEq, Eq)]
pub struct Suppression<'a> {
/// List of categories for this suppression
///
/// Categories are pair of the category name +
/// an optional category value
pub categories: Vec<(&'a Category, Option<&'a str>)>,
/// Reason for this suppression comment to exist
pub reason: &'a str,
}
pub fn parse_suppression_comment(
base: &str,
) -> impl Iterator<Item = Result<Suppression, SuppressionDiagnostic>> {
let (head, mut comment) = base.split_at(2);
let is_block_comment = match head {
"//" => false,
"/*" => {
comment = comment
.strip_suffix("*/")
.or_else(|| comment.strip_suffix(&['*', '/']))
.unwrap_or(comment);
true
}
token => panic!("comment with unknown opening token {token:?}, from {comment}"),
};
comment.lines().filter_map(move |line| {
// Eat start of line whitespace
let mut line = line.trim_start();
// If we're in a block comment eat stars, then whitespace again
if is_block_comment {
line = line.trim_start_matches('*').trim_start()
}
const PATTERNS: [[char; 2]; 11] = [
['r', 'R'],
['o', 'O'],
['m', 'M'],
['e', 'E'],
['-', '_'],
['i', 'I'],
['g', 'G'],
['n', 'N'],
['o', 'O'],
['r', 'R'],
['e', 'E'],
];
// Checks for `/rome[-_]ignore/i` without a regex, or skip the line
// entirely if it doesn't match
for pattern in PATTERNS {
line = line.strip_prefix(pattern)?;
}
let line = line.trim_start();
Some(
parse_suppression_line(line).map_err(|err| SuppressionDiagnostic {
message: err.message,
// Adjust the position of the diagnostic in the whole comment
span: err.span + offset_from(base, line),
}),
)
})
}
#[derive(Clone, Debug, PartialEq, Eq, Diagnostic)]
#[diagnostic(category = "suppressions/parse")]
pub struct SuppressionDiagnostic {
#[message]
#[description]
message: SuppressionDiagnosticKind,
#[location(span)]
span: TextRange,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum SuppressionDiagnosticKind {
MissingColon,
ParseCategory(String),
MissingCategory,
MissingParen,
}
impl std::fmt::Display for SuppressionDiagnosticKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SuppressionDiagnosticKind::MissingColon => write!(
f,
"unexpected token, expected one of ':', '(' or whitespace"
),
SuppressionDiagnosticKind::ParseCategory(category) => {
write!(f, "failed to parse category {category:?}")
}
SuppressionDiagnosticKind::MissingCategory => {
write!(f, "unexpected token, expected one of ':' or whitespace")
}
SuppressionDiagnosticKind::MissingParen => write!(f, "unexpected token, expected ')'"),
}
}
}
impl rome_console::fmt::Display for SuppressionDiagnosticKind {
fn fmt(&self, fmt: &mut rome_console::fmt::Formatter) -> std::io::Result<()> {
match self {
SuppressionDiagnosticKind::MissingColon => write!(
fmt,
"unexpected token, expected one of ':', '(' or whitespace"
),
SuppressionDiagnosticKind::ParseCategory(category) => {
write!(fmt, "failed to parse category {category:?}")
}
SuppressionDiagnosticKind::MissingCategory => {
write!(fmt, "unexpected token, expected one of ':' or whitespace")
}
SuppressionDiagnosticKind::MissingParen => {
write!(fmt, "unexpected token, expected ')'")
}
}
}
}
/// Parse the `{ <category> { (<value>) }? }+: <reason>` section of a suppression line
fn parse_suppression_line(base: &str) -> Result<Suppression, SuppressionDiagnostic> {
let mut line = base;
let mut categories = Vec::new();
loop {
// Find either a colon opening parenthesis or space
let separator = line
.find(|c: char| c == ':' || c == '(' || c.is_whitespace())
.ok_or_else(|| SuppressionDiagnostic {
message: SuppressionDiagnosticKind::MissingColon,
span: TextRange::at(offset_from(base, line), TextSize::of(line)),
})?;
let (category, rest) = line.split_at(separator);
let category = category.trim_end();
let category: Option<&'static Category> = if !category.is_empty() {
let category = category.parse().map_err(|()| SuppressionDiagnostic {
message: SuppressionDiagnosticKind::ParseCategory(category.into()),
span: TextRange::at(offset_from(base, category), TextSize::of(category)),
})?;
Some(category)
} else {
None
};
// Skip over and match the separator
let (separator, rest) = rest.split_at(1);
match separator {
// Colon token: stop parsing categories
":" => {
if let Some(category) = category {
categories.push((category, None));
}
line = rest.trim_start();
break;
}
// Paren token: parse a category + value
"(" => {
let category = category.ok_or_else(|| SuppressionDiagnostic {
message: SuppressionDiagnosticKind::MissingCategory,
span: TextRange::at(
offset_from(base, line),
offset_from(line, separator) + TextSize::of(separator),
),
})?;
let paren = rest.find(')').ok_or_else(|| SuppressionDiagnostic {
message: SuppressionDiagnosticKind::MissingParen,
span: TextRange::at(offset_from(base, rest), TextSize::of(rest)),
})?;
let (value, rest) = rest.split_at(paren);
let value = value.trim();
categories.push((category, Some(value)));
line = rest.strip_prefix(')').unwrap().trim_start();
}
// Whitespace: push a category without value
_ => {
if let Some(category) = category {
categories.push((category, None));
}
line = rest.trim_start();
}
}
}
let reason = line.trim_end();
Ok(Suppression { categories, reason })
}
/// Returns the byte offset of `substr` within `base`
///
/// # Safety
///
/// `substr` must be a substring of `base`, or calling this method will result
/// in undefined behavior.
fn offset_from(base: &str, substr: &str) -> TextSize {
let base_len = base.len();
assert!(substr.len() <= base_len);
let base = base.as_ptr();
let substr = substr.as_ptr();
let offset = unsafe { substr.offset_from(base) };
// SAFETY: converting from `isize` to `usize` can only fail if `offset` is
// negative, meaning `base` is either a substring of `substr` or the two
// string slices are unrelated
let offset = usize::try_from(offset).expect("usize underflow");
assert!(offset <= base_len);
// SAFETY: the conversion from `usize` to `TextSize` can fail if `offset`
// is larger than 2^32
TextSize::try_from(offset).expect("TextSize overflow")
}
#[cfg(test)]
mod tests {
use rome_diagnostics::category;
use rome_rowan::{TextRange, TextSize};
use crate::suppression::{offset_from, SuppressionDiagnostic, SuppressionDiagnosticKind};
use super::{parse_suppression_comment, Suppression};
#[test]
fn parse_simple_suppression() {
assert_eq!(
parse_suppression_comment("// rome-ignore parse: explanation1").collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("parse"), None)],
reason: "explanation1"
})],
);
assert_eq!(
parse_suppression_comment("/** rome-ignore parse: explanation2 */").collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("parse"), None)],
reason: "explanation2"
})],
);
assert_eq!(
parse_suppression_comment(
"/**
* rome-ignore parse: explanation3
*/"
)
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("parse"), None)],
reason: "explanation3"
})],
);
assert_eq!(
parse_suppression_comment(
"/**
* hello
* rome-ignore parse: explanation4
*/"
)
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("parse"), None)],
reason: "explanation4"
})],
);
}
#[test]
fn parse_unclosed_block_comment_suppressions() {
assert_eq!(
parse_suppression_comment("/* rome-ignore format: explanation").collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("format"), None)],
reason: "explanation"
})],
);
assert_eq!(
parse_suppression_comment("/* rome-ignore format: explanation *").collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("format"), None)],
reason: "explanation"
})],
);
assert_eq!(
parse_suppression_comment("/* rome-ignore format: explanation /").collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("format"), None)],
reason: "explanation"
})],
);
}
#[test]
fn parse_multiple_suppression() {
assert_eq!(
parse_suppression_comment("// rome-ignore parse(foo) parse(dog): explanation")
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![
(category!("parse"), Some("foo")),
(category!("parse"), Some("dog"))
],
reason: "explanation"
})],
);
assert_eq!(
parse_suppression_comment("/** rome-ignore parse(bar) parse(cat): explanation */")
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![
(category!("parse"), Some("bar")),
(category!("parse"), Some("cat"))
],
reason: "explanation"
})],
);
assert_eq!(
parse_suppression_comment(
"/**
* rome-ignore parse(yes) parse(frog): explanation
*/"
)
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![
(category!("parse"), Some("yes")),
(category!("parse"), Some("frog"))
],
reason: "explanation"
})],
);
assert_eq!(
parse_suppression_comment(
"/**
* hello
* rome-ignore parse(wow) parse(fish): explanation
*/"
)
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![
(category!("parse"), Some("wow")),
(category!("parse"), Some("fish"))
],
reason: "explanation"
})],
);
}
#[test]
fn parse_multiple_suppression_categories() {
assert_eq!(
parse_suppression_comment("// rome-ignore format lint: explanation")
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("format"), None), (category!("lint"), None)],
reason: "explanation"
})],
);
}
#[test]
fn check_offset_from() {
const BASE: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua";
assert_eq!(offset_from(BASE, BASE), TextSize::from(0));
let (_, substr) = BASE.split_at(55);
assert_eq!(offset_from(BASE, substr), TextSize::from(55));
let (_, substr) = BASE.split_at(BASE.len());
assert_eq!(offset_from(BASE, substr), TextSize::of(BASE));
}
#[test]
fn diagnostic_missing_colon() {
assert_eq!(
parse_suppression_comment("// rome-ignore format explanation").collect::<Vec<_>>(),
vec![Err(SuppressionDiagnostic {
message: SuppressionDiagnosticKind::MissingColon,
span: TextRange::new(TextSize::from(22), TextSize::from(33))
})],
);
}
#[test]
fn diagnostic_missing_paren() {
assert_eq!(
parse_suppression_comment("// rome-ignore format(:").collect::<Vec<_>>(),
vec![Err(SuppressionDiagnostic {
message: SuppressionDiagnosticKind::MissingParen,
span: TextRange::new(TextSize::from(22), TextSize::from(23))
})],
);
}
#[test]
fn diagnostic_missing_category() {
assert_eq!(
parse_suppression_comment("// rome-ignore (value): explanation").collect::<Vec<_>>(),
vec![Err(SuppressionDiagnostic {
message: SuppressionDiagnosticKind::MissingCategory,
span: TextRange::new(TextSize::from(15), TextSize::from(16))
})],
);
}
#[test]
fn diagnostic_unknown_category() {
assert_eq!(
parse_suppression_comment("// rome-ignore unknown: explanation").collect::<Vec<_>>(),
vec![Err(SuppressionDiagnostic {
message: SuppressionDiagnosticKind::ParseCategory(String::from("unknown")),
span: TextRange::new(TextSize::from(15), TextSize::from(22))
})],
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/modifier_ext.rs | crates/rome_js_syntax/src/modifier_ext.rs | use crate::{
AnyJsMethodModifier, AnyJsPropertyModifier, AnyTsIndexSignatureModifier,
AnyTsMethodSignatureModifier, AnyTsPropertyParameterModifier, AnyTsPropertySignatureModifier,
JsSyntaxKind, TsAccessibilityModifier,
};
/// Helpful data structure to make the order modifiers predictable inside the formatter
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq)]
pub enum Modifiers {
// modifiers must be sorted by precedence.
Decorator,
Accessibility,
Declare,
Static,
Abstract,
Override,
Readonly,
Accessor,
}
impl From<&AnyTsIndexSignatureModifier> for Modifiers {
fn from(modifier: &AnyTsIndexSignatureModifier) -> Self {
match modifier {
AnyTsIndexSignatureModifier::JsStaticModifier(_) => Modifiers::Static,
AnyTsIndexSignatureModifier::TsReadonlyModifier(_) => Modifiers::Readonly,
}
}
}
impl From<&AnyJsMethodModifier> for Modifiers {
fn from(modifier: &AnyJsMethodModifier) -> Self {
match modifier {
AnyJsMethodModifier::JsDecorator(_) => Modifiers::Decorator,
AnyJsMethodModifier::JsStaticModifier(_) => Modifiers::Static,
AnyJsMethodModifier::TsAccessibilityModifier(_) => Modifiers::Accessibility,
AnyJsMethodModifier::TsOverrideModifier(_) => Modifiers::Override,
}
}
}
impl From<&AnyTsMethodSignatureModifier> for Modifiers {
fn from(modifier: &AnyTsMethodSignatureModifier) -> Self {
match modifier {
AnyTsMethodSignatureModifier::JsDecorator(_) => Modifiers::Decorator,
AnyTsMethodSignatureModifier::JsStaticModifier(_) => Modifiers::Static,
AnyTsMethodSignatureModifier::TsAbstractModifier(_) => Modifiers::Abstract,
AnyTsMethodSignatureModifier::TsAccessibilityModifier(_) => Modifiers::Accessibility,
AnyTsMethodSignatureModifier::TsOverrideModifier(_) => Modifiers::Override,
}
}
}
impl From<&AnyJsPropertyModifier> for Modifiers {
fn from(modifier: &AnyJsPropertyModifier) -> Self {
match modifier {
AnyJsPropertyModifier::JsDecorator(_) => Modifiers::Decorator,
AnyJsPropertyModifier::JsStaticModifier(_) => Modifiers::Static,
AnyJsPropertyModifier::JsAccessorModifier(_) => Modifiers::Accessor,
AnyJsPropertyModifier::TsAccessibilityModifier(_) => Modifiers::Accessibility,
AnyJsPropertyModifier::TsOverrideModifier(_) => Modifiers::Override,
AnyJsPropertyModifier::TsReadonlyModifier(_) => Modifiers::Readonly,
}
}
}
impl From<&AnyTsPropertyParameterModifier> for Modifiers {
fn from(modifier: &AnyTsPropertyParameterModifier) -> Self {
match modifier {
AnyTsPropertyParameterModifier::TsAccessibilityModifier(_) => Modifiers::Accessibility,
AnyTsPropertyParameterModifier::TsOverrideModifier(_) => Modifiers::Override,
AnyTsPropertyParameterModifier::TsReadonlyModifier(_) => Modifiers::Readonly,
}
}
}
impl From<&AnyTsPropertySignatureModifier> for Modifiers {
fn from(modifier: &AnyTsPropertySignatureModifier) -> Self {
match modifier {
AnyTsPropertySignatureModifier::JsDecorator(_) => Modifiers::Decorator,
AnyTsPropertySignatureModifier::TsAccessibilityModifier(_) => Modifiers::Accessibility,
AnyTsPropertySignatureModifier::TsDeclareModifier(_) => Modifiers::Declare,
AnyTsPropertySignatureModifier::JsStaticModifier(_) => Modifiers::Static,
AnyTsPropertySignatureModifier::JsAccessorModifier(_) => Modifiers::Accessor,
AnyTsPropertySignatureModifier::TsAbstractModifier(_) => Modifiers::Abstract,
AnyTsPropertySignatureModifier::TsOverrideModifier(_) => Modifiers::Override,
AnyTsPropertySignatureModifier::TsReadonlyModifier(_) => Modifiers::Readonly,
}
}
}
impl TsAccessibilityModifier {
/// Is `self` the `private` accessibility modifier?
///
/// ## Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::T;
///
/// let modifier = make::ts_accessibility_modifier(make::token(T![private]));
///
/// assert!(modifier.is_private());
/// ```
pub fn is_private(&self) -> bool {
if let Ok(modifier_token) = self.modifier_token() {
modifier_token.kind() == JsSyntaxKind::PRIVATE_KW
} else {
false
}
}
/// Is `self` the `protected` accessibility modifier?
///
/// ## Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::T;
///
/// let modifier = make::ts_accessibility_modifier(make::token(T![protected]));
///
/// assert!(modifier.is_protected());
/// ```
pub fn is_protected(&self) -> bool {
if let Ok(modifier_token) = self.modifier_token() {
modifier_token.kind() == JsSyntaxKind::PROTECTED_KW
} else {
false
}
}
/// Is `self` the `public` accessibility modifier?
///
/// ## Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::T;
///
/// let modifier = make::ts_accessibility_modifier(make::token(T![public]));
///
/// assert!(modifier.is_public());
/// ```
pub fn is_public(&self) -> bool {
if let Ok(modifier_token) = self.modifier_token() {
modifier_token.kind() == JsSyntaxKind::PUBLIC_KW
} else {
false
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/stmt_ext.rs | crates/rome_js_syntax/src/stmt_ext.rs | //! Extended AST node definitions for statements which are unique and special enough to generate code for manually
use crate::{
AnyJsArrayAssignmentPatternElement, AnyJsAssignmentPattern, AnyJsSwitchClause,
JsForVariableDeclaration, JsStatementList, JsSyntaxToken as SyntaxToken, JsVariableDeclaration,
TsModuleDeclaration, T,
};
use rome_rowan::{declare_node_union, SyntaxResult};
impl AnyJsSwitchClause {
pub fn clause_token(&self) -> SyntaxResult<SyntaxToken> {
match &self {
AnyJsSwitchClause::JsCaseClause(item) => item.case_token(),
AnyJsSwitchClause::JsDefaultClause(item) => item.default_token(),
}
}
pub fn colon_token(&self) -> SyntaxResult<SyntaxToken> {
match &self {
AnyJsSwitchClause::JsCaseClause(item) => item.colon_token(),
AnyJsSwitchClause::JsDefaultClause(item) => item.colon_token(),
}
}
pub fn consequent(&self) -> JsStatementList {
match &self {
AnyJsSwitchClause::JsCaseClause(item) => item.consequent(),
AnyJsSwitchClause::JsDefaultClause(item) => item.consequent(),
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum JsVariableKind {
Const,
Let,
Var,
Using,
}
impl JsVariableDeclaration {
/// Whether the declaration is a const declaration
pub fn is_const(&self) -> bool {
self.variable_kind() == Ok(JsVariableKind::Const)
}
/// Whether the declaration is a let declaration
pub fn is_let(&self) -> bool {
self.variable_kind() == Ok(JsVariableKind::Let)
}
/// Whether the declaration is a var declaration
pub fn is_var(&self) -> bool {
self.variable_kind() == Ok(JsVariableKind::Var)
}
pub fn variable_kind(&self) -> SyntaxResult<JsVariableKind> {
let token_kind = self.kind().map(|t| t.kind())?;
Ok(match token_kind {
T![const] => JsVariableKind::Const,
T![let] => JsVariableKind::Let,
T![var] => JsVariableKind::Var,
T![using] => JsVariableKind::Using,
_ => unreachable!(),
})
}
}
impl JsForVariableDeclaration {
/// Whether the declaration is a const declaration
pub fn is_const(&self) -> bool {
self.variable_kind() == Ok(JsVariableKind::Const)
}
/// Whether the declaration is a let declaration
pub fn is_let(&self) -> bool {
self.variable_kind() == Ok(JsVariableKind::Let)
}
/// Whether the declaration is a var declaration
pub fn is_var(&self) -> bool {
self.variable_kind() == Ok(JsVariableKind::Var)
}
pub fn variable_kind(&self) -> SyntaxResult<JsVariableKind> {
let token_kind = self.kind_token().map(|t| t.kind())?;
Ok(match token_kind {
T![const] => JsVariableKind::Const,
T![let] => JsVariableKind::Let,
T![var] => JsVariableKind::Var,
T![using] => JsVariableKind::Using,
_ => unreachable!(),
})
}
}
declare_node_union! {
pub AnyJsVariableDeclaration = JsVariableDeclaration | JsForVariableDeclaration
}
impl AnyJsVariableDeclaration {
pub fn variable_kind(&self) -> SyntaxResult<JsVariableKind> {
match self {
AnyJsVariableDeclaration::JsForVariableDeclaration(decl) => decl.variable_kind(),
AnyJsVariableDeclaration::JsVariableDeclaration(decl) => decl.variable_kind(),
}
}
}
impl AnyJsArrayAssignmentPatternElement {
pub fn pattern(self) -> Option<AnyJsAssignmentPattern> {
match self {
Self::AnyJsAssignmentPattern(p) => Some(p),
Self::JsArrayAssignmentPatternRestElement(p) => p.pattern().ok(),
Self::JsAssignmentWithDefault(p) => p.pattern().ok(),
Self::JsArrayHole(_) => None,
}
}
}
impl TsModuleDeclaration {
pub fn is_module(&self) -> SyntaxResult<bool> {
Ok(self.module_or_namespace()?.kind() == T![module])
}
pub fn is_namespace(&self) -> SyntaxResult<bool> {
Ok(self.module_or_namespace()?.kind() == T![namespace])
}
}
#[cfg(test)]
mod tests {
use rome_js_factory::syntax::{JsSyntaxKind::*, JsVariableDeclaration};
use rome_js_factory::JsSyntaxTreeBuilder;
use rome_rowan::AstNode;
#[test]
fn is_var_check() {
let mut tree_builder = JsSyntaxTreeBuilder::new();
tree_builder.start_node(JS_VARIABLE_DECLARATION);
tree_builder.token(VAR_KW, "var");
tree_builder.start_node(JS_VARIABLE_DECLARATOR_LIST);
tree_builder.start_node(JS_VARIABLE_DECLARATOR);
tree_builder.start_node(JS_IDENTIFIER_BINDING);
tree_builder.token(IDENT, "a");
tree_builder.finish_node();
tree_builder.finish_node(); // declarator
tree_builder.finish_node(); // list
tree_builder.finish_node(); // declaration
let root = tree_builder.finish();
let var_decl = JsVariableDeclaration::cast(root).unwrap();
assert!(var_decl.is_var());
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/syntax_node.rs | crates/rome_js_syntax/src/syntax_node.rs | //! This module defines the Concrete Syntax Tree used by Rome.
//!
//! The tree is entirely lossless, whitespace, comments, and errors are preserved.
//! It also provides traversal methods including parent, children, and siblings of nodes.
//!
//! This is a simple wrapper around the `rowan` crate which does most of the heavy lifting and is language agnostic.
use crate::{AnyJsRoot, JsSyntaxKind};
use rome_rowan::Language;
#[cfg(feature = "serde")]
use serde::Serialize;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, schemars::JsonSchema))]
pub struct JsLanguage;
impl Language for JsLanguage {
type Kind = JsSyntaxKind;
type Root = AnyJsRoot;
}
pub type JsSyntaxNode = rome_rowan::SyntaxNode<JsLanguage>;
pub type JsSyntaxToken = rome_rowan::SyntaxToken<JsLanguage>;
pub type JsSyntaxElement = rome_rowan::SyntaxElement<JsLanguage>;
pub type JsSyntaxNodeChildren = rome_rowan::SyntaxNodeChildren<JsLanguage>;
pub type JsSyntaxElementChildren = rome_rowan::SyntaxElementChildren<JsLanguage>;
pub type JsSyntaxList = rome_rowan::SyntaxList<JsLanguage>;
pub type JsSyntaxTrivia = rome_rowan::syntax::SyntaxTrivia<JsLanguage>;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/directive_ext.rs | crates/rome_js_syntax/src/directive_ext.rs | use rome_rowan::{SyntaxResult, TokenText};
use crate::{inner_string_text, JsDirective};
impl JsDirective {
/// Get the inner text of a string not including the quotes
///
/// ## Examples
///
/// ```
/// use rome_js_factory::syntax::{JsDirective, JsSyntaxKind::*};
/// use rome_js_factory::JsSyntaxTreeBuilder;
/// use rome_rowan::AstNode;
/// let mut tree_builder = JsSyntaxTreeBuilder::new();
/// tree_builder.start_node(JS_DIRECTIVE);
/// tree_builder.token(JS_STRING_LITERAL, "\"use strict\"");
/// tree_builder.finish_node();
/// let node = tree_builder.finish();
/// let js_directive = JsDirective::cast(node).unwrap();
/// let text = js_directive.inner_string_text().unwrap();
/// assert_eq!(text, "use strict")
/// ```
pub fn inner_string_text(&self) -> SyntaxResult<TokenText> {
Ok(inner_string_text(&self.value_token()?))
}
}
#[cfg(test)]
mod tests {
use rome_js_factory::syntax::{JsDirective, JsSyntaxKind::*};
use rome_js_factory::JsSyntaxTreeBuilder;
use rome_rowan::AstNode;
#[test]
fn js_directive_inner_string_text() {
let tokens = vec!["\"use strict\"", "'use strict'"];
for token in tokens {
let mut tree_builder = JsSyntaxTreeBuilder::new();
tree_builder.start_node(JS_DIRECTIVE);
tree_builder.token(JS_STRING_LITERAL, token);
tree_builder.finish_node();
let node = tree_builder.finish();
let js_directive = JsDirective::cast(node).unwrap();
let text = js_directive.inner_string_text().unwrap();
assert_eq!(text, "use strict")
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/jsx_ext.rs | crates/rome_js_syntax/src/jsx_ext.rs | use std::collections::HashSet;
use crate::{
inner_string_text, static_value::StaticValue, AnyJsxAttribute, AnyJsxAttributeName,
AnyJsxAttributeValue, AnyJsxChild, AnyJsxElementName, JsSyntaxToken, JsxAttribute,
JsxAttributeList, JsxElement, JsxName, JsxOpeningElement, JsxSelfClosingElement, JsxString,
};
use rome_rowan::{declare_node_union, AstNode, AstNodeList, SyntaxResult, TokenText};
impl JsxString {
/// Get the inner text of a string not including the quotes
///
/// ## Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_rowan::TriviaPieceKind;
///
///let string = make::jsx_string(make::jsx_string_literal("button")
/// .with_leading_trivia(vec![(TriviaPieceKind::Whitespace, " ")]));
/// assert_eq!(string.inner_string_text().unwrap().text(), "button");
/// ```
pub fn inner_string_text(&self) -> SyntaxResult<TokenText> {
Ok(inner_string_text(&self.value_token()?))
}
}
impl JsxOpeningElement {
/// Find and return the `JsxAttribute` that matches the given name
///
/// ## Examples
///
/// ```
///
/// use rome_js_factory::make;
/// use rome_js_factory::make::{ident, jsx_attribute, jsx_name, jsx_opening_element, token, jsx_attribute_list};
/// use rome_js_syntax::{AnyJsxAttribute, AnyJsxAttributeName, AnyJsxElementName, T};
///
/// let div = AnyJsxAttribute::JsxAttribute(jsx_attribute(
/// AnyJsxAttributeName::JsxName(
/// jsx_name(ident("div"))
/// )
/// ).build());
///
/// let img = AnyJsxAttribute::JsxAttribute(jsx_attribute(
/// AnyJsxAttributeName::JsxName(
/// jsx_name(ident("img"))
/// )
/// ).build());
///
/// let attributes = jsx_attribute_list(vec![
/// div,
/// img
/// ]);
///
/// let opening_element = jsx_opening_element(
/// token(T![<]),
/// AnyJsxElementName::JsxName(
/// jsx_name(ident("Test"))
/// ),
/// attributes,
/// token(T![>]),
/// ).build();
///
/// assert_eq!(opening_element.find_attribute_by_name("div").unwrap().is_some(), true);
/// assert_eq!(opening_element.find_attribute_by_name("img").unwrap().is_some(), true);
/// assert_eq!(opening_element.find_attribute_by_name("p").unwrap().is_some(), false);
/// ```
///
pub fn find_attribute_by_name(
&self,
name_to_lookup: &str,
) -> SyntaxResult<Option<JsxAttribute>> {
self.attributes().find_by_name(name_to_lookup)
}
/// It checks if current attribute has a trailing spread props
///
/// ## Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_factory::make::{ident, jsx_attribute, jsx_name, jsx_opening_element, token, jsx_attribute_list, jsx_self_closing_element, jsx_spread_attribute, jsx_ident, js_identifier_expression, js_reference_identifier};
/// use rome_js_syntax::{AnyJsExpression, AnyJsxAttribute, AnyJsxAttributeName, AnyJsxElementName, T};
///
/// let div = AnyJsxAttribute::JsxAttribute(jsx_attribute(
/// AnyJsxAttributeName::JsxName(
/// jsx_name(ident("div"))
/// )
/// ).build());
///
/// let spread = AnyJsxAttribute::JsxSpreadAttribute(jsx_spread_attribute(
/// token(T!['{']),
/// token(T![...]),
/// AnyJsExpression::JsIdentifierExpression(js_identifier_expression(
/// js_reference_identifier(ident("spread"))
/// )),
/// token(T!['}']),
/// ));
///
///
///
/// let attributes = jsx_attribute_list(vec![
/// div,
/// spread
/// ]);
///
/// let opening_element = jsx_opening_element(
/// token(T![<]),
/// AnyJsxElementName::JsxName(
/// jsx_name(ident("Test"))
/// ),
/// attributes,
/// token(T![>]),
/// ).build();
///
/// let div = opening_element.find_attribute_by_name("div").unwrap().unwrap();
/// assert!(opening_element.has_trailing_spread_prop(div.clone()));
/// ```
pub fn has_trailing_spread_prop(&self, current_attribute: impl Into<AnyJsxAttribute>) -> bool {
self.attributes()
.has_trailing_spread_prop(current_attribute)
}
/// Check if jsx element has a child that is accessible
pub fn has_accessible_child(&self) -> bool {
self.parent::<JsxElement>().map_or(false, |parent| {
parent
.children()
.into_iter()
.any(|child| child.is_accessible_node().unwrap_or(true))
})
}
}
impl JsxSelfClosingElement {
/// Find and return the `JsxAttribute` that matches the given name
///
/// ## Examples
///
/// ```
///
/// use rome_js_factory::make;
/// use rome_js_factory::make::{ident, jsx_attribute, jsx_name, jsx_opening_element, token, jsx_attribute_list, jsx_self_closing_element};
/// use rome_js_syntax::{AnyJsxAttribute, AnyJsxAttributeName, AnyJsxElementName, T};
///
/// let div = AnyJsxAttribute::JsxAttribute(jsx_attribute(
/// AnyJsxAttributeName::JsxName(
/// jsx_name(ident("div"))
/// )
/// ).build());
///
/// let img = AnyJsxAttribute::JsxAttribute(jsx_attribute(
/// AnyJsxAttributeName::JsxName(
/// jsx_name(ident("img"))
/// )
/// ).build());
///
/// let attributes = jsx_attribute_list(vec![
/// div,
/// img
/// ]);
///
/// let opening_element = jsx_self_closing_element(
/// token(T![<]),
/// AnyJsxElementName::JsxName(
/// jsx_name(ident("Test"))
/// ),
/// attributes,
/// token(T![/]),
/// token(T![>]),
/// ).build();
///
/// assert_eq!(opening_element.find_attribute_by_name("div").unwrap().is_some(), true);
/// assert_eq!(opening_element.find_attribute_by_name("img").unwrap().is_some(), true);
/// assert_eq!(opening_element.find_attribute_by_name("p").unwrap().is_some(), false);
/// ```
///
pub fn find_attribute_by_name(
&self,
name_to_lookup: &str,
) -> SyntaxResult<Option<JsxAttribute>> {
self.attributes().find_by_name(name_to_lookup)
}
/// It checks if current attribute has a trailing spread props
///
/// ## Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_factory::make::{ident, jsx_attribute, jsx_name, jsx_opening_element, token, jsx_attribute_list, jsx_self_closing_element, jsx_spread_attribute, jsx_ident, js_identifier_expression, js_reference_identifier};
/// use rome_js_syntax::{AnyJsExpression, AnyJsxAttribute, AnyJsxAttributeName, AnyJsxElementName, T};
///
/// let div = AnyJsxAttribute::JsxAttribute(jsx_attribute(
/// AnyJsxAttributeName::JsxName(
/// jsx_name(ident("div"))
/// )
/// ).build());
///
/// let spread = AnyJsxAttribute::JsxSpreadAttribute(jsx_spread_attribute(
/// token(T!['{']),
/// token(T![...]),
/// AnyJsExpression::JsIdentifierExpression(js_identifier_expression(
/// js_reference_identifier(ident("spread"))
/// )),
/// token(T!['}']),
/// ));
///
///
///
/// let attributes = jsx_attribute_list(vec![
/// div,
/// spread
/// ]);
///
/// let opening_element = jsx_self_closing_element(
/// token(T![<]),
/// AnyJsxElementName::JsxName(
/// jsx_name(ident("Test"))
/// ),
/// attributes,
/// token(T![/]),
/// token(T![>]),
/// ).build();
///
/// let div = opening_element.find_attribute_by_name("div").unwrap().unwrap();
/// assert!(opening_element.has_trailing_spread_prop(div.clone()));
/// ```
pub fn has_trailing_spread_prop(&self, current_attribute: impl Into<AnyJsxAttribute>) -> bool {
self.attributes()
.has_trailing_spread_prop(current_attribute)
}
}
impl JsxAttributeList {
/// Finds and returns attributes `JsxAttribute` that matches the given names like [Self::find_by_name].
/// Only attributes with name as [JsxName] can be returned.
///
/// Each name of "names_to_lookup" should be unique.
///
/// Supports maximum of 16 names to avoid stack overflow. Each attribute will consume:
///
/// - 8 bytes for the `Option<JsxAttribute>` result;
/// - plus 16 bytes for the [&str] argument.
pub fn find_by_names<const N: usize>(
&self,
names_to_lookup: [&str; N],
) -> [Option<JsxAttribute>; N] {
// assert there are no duplicates
debug_assert!(HashSet::<_>::from_iter(names_to_lookup).len() == N);
debug_assert!(N <= 16);
const INIT: Option<JsxAttribute> = None;
let mut results = [INIT; N];
let mut missing = N;
'attributes: for att in self {
if let Some(attribute) = att.as_jsx_attribute() {
if let Some(name) = attribute
.name()
.ok()
.and_then(|x| x.as_jsx_name()?.value_token().ok())
{
let name = name.text_trimmed();
for i in 0..N {
if results[i].is_none() && names_to_lookup[i] == name {
results[i] = Some(attribute.clone());
if missing == 1 {
break 'attributes;
} else {
missing -= 1;
break;
}
}
}
}
}
}
results
}
pub fn find_by_name(&self, name_to_lookup: &str) -> SyntaxResult<Option<JsxAttribute>> {
let attribute = self.iter().find_map(|attribute| {
let attribute = JsxAttribute::cast_ref(attribute.syntax())?;
let name = attribute.name().ok()?;
let name = JsxName::cast_ref(name.syntax())?;
if name.value_token().ok()?.text_trimmed() == name_to_lookup {
Some(attribute)
} else {
None
}
});
Ok(attribute)
}
pub fn has_trailing_spread_prop(&self, current_attribute: impl Into<AnyJsxAttribute>) -> bool {
let mut current_attribute_found = false;
let current_attribute = current_attribute.into();
for attribute in self {
if attribute == current_attribute {
current_attribute_found = true;
continue;
}
if current_attribute_found && attribute.as_jsx_spread_attribute().is_some() {
return true;
}
}
false
}
}
impl AnyJsxElementName {
pub fn name_value_token(&self) -> Option<JsSyntaxToken> {
match self {
AnyJsxElementName::JsxMemberName(member) => member.member().ok()?.value_token().ok(),
AnyJsxElementName::JsxName(name) => name.value_token().ok(),
AnyJsxElementName::JsxNamespaceName(name) => name.name().ok()?.value_token().ok(),
AnyJsxElementName::JsxReferenceIdentifier(name) => name.value_token().ok(),
}
}
}
declare_node_union! {
pub AnyJsxElement = JsxOpeningElement | JsxSelfClosingElement
}
impl AnyJsxElement {
pub fn attributes(&self) -> JsxAttributeList {
match self {
AnyJsxElement::JsxOpeningElement(element) => element.attributes(),
AnyJsxElement::JsxSelfClosingElement(element) => element.attributes(),
}
}
pub fn name(&self) -> SyntaxResult<AnyJsxElementName> {
match self {
AnyJsxElement::JsxOpeningElement(element) => element.name(),
AnyJsxElement::JsxSelfClosingElement(element) => element.name(),
}
}
pub fn name_value_token(&self) -> Option<JsSyntaxToken> {
self.name().ok()?.name_value_token()
}
/// Return true if the current element is actually a component
///
/// - `<Span />` is a component and it would return `true`
/// - `<span ></span>` is **not** component and it returns `false`
pub fn is_custom_component(&self) -> bool {
self.name().map_or(false, |it| it.as_jsx_name().is_none())
}
/// Return true if the current element is an HTML element
///
/// - `<Span />` is a component and it would return `false`
/// - `<span ></span>` is **not** component and it returns `true`
pub fn is_element(&self) -> bool {
self.name().map_or(false, |it| it.as_jsx_name().is_some())
}
pub fn has_spread_prop(&self) -> bool {
self.attributes()
.into_iter()
.any(|attribute| matches!(attribute, AnyJsxAttribute::JsxSpreadAttribute(_)))
}
pub fn has_trailing_spread_prop(&self, current_attribute: impl Into<AnyJsxAttribute>) -> bool {
match self {
AnyJsxElement::JsxSelfClosingElement(element) => {
element.has_trailing_spread_prop(current_attribute)
}
AnyJsxElement::JsxOpeningElement(element) => {
element.has_trailing_spread_prop(current_attribute)
}
}
}
pub fn find_attribute_by_name(&self, name_to_lookup: &str) -> Option<JsxAttribute> {
match self {
AnyJsxElement::JsxSelfClosingElement(element) => {
element.find_attribute_by_name(name_to_lookup).ok()?
}
AnyJsxElement::JsxOpeningElement(element) => {
element.find_attribute_by_name(name_to_lookup).ok()?
}
}
}
pub fn has_truthy_attribute(&self, name_to_lookup: &str) -> bool {
self.find_attribute_by_name(name_to_lookup)
.map_or(false, |attribute| {
attribute
.as_static_value()
.map_or(true, |value| !(value.is_falsy() || value.text() == "false"))
&& !self.has_trailing_spread_prop(attribute)
})
}
}
impl JsxAttribute {
pub fn is_value_null_or_undefined(&self) -> bool {
self.as_static_value()
.map_or(false, |it| it.is_null_or_undefined())
}
pub fn as_static_value(&self) -> Option<StaticValue> {
self.initializer()?.value().ok()?.as_static_value()
}
pub fn name_value_token(&self) -> Option<JsSyntaxToken> {
match self.name().ok()? {
AnyJsxAttributeName::JsxName(name) => name.value_token().ok(),
AnyJsxAttributeName::JsxNamespaceName(name) => name.name().ok()?.value_token().ok(),
}
}
}
impl AnyJsxAttributeValue {
pub fn is_value_null_or_undefined(&self) -> bool {
self.as_static_value()
.map_or(false, |it| it.is_null_or_undefined())
}
pub fn as_static_value(&self) -> Option<StaticValue> {
match self {
AnyJsxAttributeValue::AnyJsxTag(_) => None,
AnyJsxAttributeValue::JsxExpressionAttributeValue(expression) => {
expression.expression().ok()?.as_static_value()
}
AnyJsxAttributeValue::JsxString(string) => {
Some(StaticValue::String(string.value_token().ok()?))
}
}
}
}
impl AnyJsxChild {
/// Check if jsx child node is accessible for screen readers
pub fn is_accessible_node(&self) -> Option<bool> {
Some(match self {
AnyJsxChild::JsxText(text) => {
let value_token = text.value_token().ok()?;
value_token.text_trimmed().trim() != ""
}
AnyJsxChild::JsxExpressionChild(expression) => {
let expression = expression.expression()?;
expression
.as_static_value()
.map_or(true, |value| !value.is_falsy())
}
AnyJsxChild::JsxElement(element) => {
let opening_element = element.opening_element().ok()?;
let jsx_element = AnyJsxElement::cast(opening_element.syntax().clone())?;
// We don't check if a component (e.g. <Text aria-hidden />) is using the `aria-hidden` property,
// since we don't have enough information about how the property is used.
jsx_element.is_custom_component()
|| !jsx_element.has_truthy_attribute("aria-hidden")
}
AnyJsxChild::JsxSelfClosingElement(element) => {
let jsx_element = AnyJsxElement::cast(element.syntax().clone())?;
jsx_element.is_custom_component()
|| !jsx_element.has_truthy_attribute("aria-hidden")
}
AnyJsxChild::JsxFragment(fragment) => fragment
.children()
.into_iter()
.any(|child| child.is_accessible_node().unwrap_or(true)),
_ => true,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/file_source.rs | crates/rome_js_syntax/src/file_source.rs | use crate::JsLanguage;
use rome_rowan::{FileSource, FileSourceError};
use std::path::Path;
/// Enum of the different ECMAScript standard versions.
/// The versions are ordered in increasing order; The newest version comes last.
///
/// Defaults to the latest stable ECMAScript standard.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum LanguageVersion {
ES2022,
/// The next, not yet finalized ECMAScript version
ESNext,
}
impl LanguageVersion {
/// Returns the latest finalized ECMAScript version
pub const fn latest() -> Self {
LanguageVersion::ES2022
}
}
impl Default for LanguageVersion {
fn default() -> Self {
Self::latest()
}
}
/// Is the source file an ECMAScript Module or Script.
/// Changes the parsing semantic.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
pub enum ModuleKind {
/// An ECMAScript [Script](https://tc39.es/ecma262/multipage/ecmascript-language-scripts-and-modules.html#sec-scripts)
Script,
/// AN ECMAScript [Module](https://tc39.es/ecma262/multipage/ecmascript-language-scripts-and-modules.html#sec-modules)
#[default]
Module,
}
impl ModuleKind {
pub const fn is_script(&self) -> bool {
matches!(self, ModuleKind::Script)
}
pub const fn is_module(&self) -> bool {
matches!(self, ModuleKind::Module)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
pub enum LanguageVariant {
/// Standard JavaScript or TypeScript syntax without any extensions
#[default]
Standard,
/// Allows JSX syntax inside a JavaScript or TypeScript file
Jsx,
}
impl LanguageVariant {
pub const fn is_standard(&self) -> bool {
matches!(self, LanguageVariant::Standard)
}
pub const fn is_jsx(&self) -> bool {
matches!(self, LanguageVariant::Jsx)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
pub enum Language {
#[default]
JavaScript,
/// TypeScript source with or without JSX.
/// `definition_file` must be true for `d.ts` files.
TypeScript { definition_file: bool },
}
impl Language {
pub const fn is_javascript(&self) -> bool {
matches!(self, Language::JavaScript)
}
pub const fn is_typescript(&self) -> bool {
matches!(self, Language::TypeScript { .. })
}
pub const fn is_definition_file(&self) -> bool {
matches!(
self,
Language::TypeScript {
definition_file: true
}
)
}
}
impl<'a> FileSource<'a, JsLanguage> for JsFileSource {}
#[derive(Clone, Copy, Debug, Default)]
pub struct JsFileSource {
language: Language,
variant: LanguageVariant,
module_kind: ModuleKind,
version: LanguageVersion,
}
impl JsFileSource {
/// language: JS, variant: Standard, module_kind: Module, version: Latest
pub fn js_module() -> Self {
Self::default()
}
/// language: JS, variant: Standard, module_kind: Script, version: Latest
pub fn js_script() -> Self {
Self::default().with_module_kind(ModuleKind::Script)
}
/// language: JS, variant: JSX, module_kind: Module, version: Latest
pub fn jsx() -> JsFileSource {
Self::js_module().with_variant(LanguageVariant::Jsx)
}
/// language: TS, variant: Standard, module_kind: Module, version: Latest
pub fn ts() -> JsFileSource {
Self {
language: Language::TypeScript {
definition_file: false,
},
..Self::default()
}
}
/// language: TS, variant: JSX, module_kind: Module, version: Latest
pub fn tsx() -> JsFileSource {
Self::ts().with_variant(LanguageVariant::Jsx)
}
/// TypeScript definition file
/// language: TS, ambient, variant: Standard, module_kind: Module, version: Latest
pub fn d_ts() -> JsFileSource {
Self {
language: Language::TypeScript {
definition_file: true,
},
..Self::default()
}
}
pub const fn with_module_kind(mut self, kind: ModuleKind) -> Self {
self.module_kind = kind;
self
}
pub const fn with_version(mut self, version: LanguageVersion) -> Self {
self.version = version;
self
}
pub const fn with_variant(mut self, variant: LanguageVariant) -> Self {
self.variant = variant;
self
}
pub fn language(&self) -> Language {
self.language
}
pub fn variant(&self) -> LanguageVariant {
self.variant
}
pub fn version(&self) -> LanguageVersion {
self.version
}
pub const fn module_kind(&self) -> ModuleKind {
self.module_kind
}
pub const fn is_module(&self) -> bool {
self.module_kind.is_module()
}
pub fn file_extension(&self) -> &str {
match self.language {
Language::JavaScript => {
if matches!(self.variant, LanguageVariant::Jsx) {
return "jsx";
}
match self.module_kind {
ModuleKind::Script => "cjs",
ModuleKind::Module => "js",
}
}
Language::TypeScript { .. } => {
if matches!(self.variant, LanguageVariant::Jsx) {
"tsx"
} else {
"ts"
}
}
}
}
}
impl TryFrom<&Path> for JsFileSource {
type Error = FileSourceError;
fn try_from(path: &Path) -> Result<Self, Self::Error> {
let file_name = path
.file_name()
.ok_or_else(|| FileSourceError::MissingFileName(path.into()))?
.to_str()
.ok_or_else(|| FileSourceError::MissingFileName(path.into()))?;
let extension = path
.extension()
.ok_or_else(|| FileSourceError::MissingFileExtension(path.into()))?
.to_str()
.ok_or_else(|| FileSourceError::MissingFileExtension(path.into()))?;
compute_source_type_from_path_or_extension(file_name, extension)
}
}
/// It deduce the [JsFileSource] from the file name and its extension
fn compute_source_type_from_path_or_extension(
file_name: &str,
extension: &str,
) -> Result<JsFileSource, FileSourceError> {
let source_type = if file_name.ends_with(".d.ts")
|| file_name.ends_with(".d.mts")
|| file_name.ends_with(".d.cts")
{
JsFileSource::d_ts()
} else {
match extension {
"cjs" => JsFileSource::js_module().with_module_kind(ModuleKind::Script),
"js" | "mjs" | "jsx" => JsFileSource::jsx(),
"ts" | "mts" | "cts" => JsFileSource::ts(),
"tsx" => JsFileSource::tsx(),
_ => {
return Err(FileSourceError::UnknownExtension(
file_name.into(),
extension.into(),
))
}
}
};
Ok(source_type)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.