fix(rome_js_analyze): add code action for `noUnusedVariables`
MODIFY
crates/rome_js_analyze/src/lib.rs
crates/rome_js_analyze/src/lib.rs
@@ -141,7 +141,7 @@ mod tests {
String::from_utf8(buffer).unwrap()
}
- const SOURCE: &str = r#"<input disabled />
+ const SOURCE: &str = r#"function f(a, b) { b; }
"#;
let parsed = parse(SOURCE, FileId::zero(), SourceType::jsx());

MODIFY
crates/rome_js_analyze/src/semantic_analyzers/nursery/no_unused_variables.rs
crates/rome_js_analyze/src/semantic_analyzers/nursery/no_unused_variables.rs
use crate::semantic_services::Semantic;
-use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic};
+use crate::JsRuleAction;
+use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Rule, RuleDiagnostic};
use rome_console::markup;
+use rome_diagnostics::Applicability;
+use rome_js_factory::make::{ident, js_identifier_binding};
use rome_js_semantic::{AllReferencesExtensions, SemanticScopeExtensions};
use rome_js_syntax::{
JsClassExpression, JsConstructorParameterList, JsConstructorParameters, JsFunctionDeclaration,
JsFunctionExpression, JsIdentifierBinding, JsParameterList, JsParameters, JsSyntaxKind,
JsVariableDeclarator, TsDeclareStatement, TsPropertyParameter,
};
-use rome_rowan::{AstNode, SyntaxNodeCast};
+use rome_rowan::{AstNode, BatchMutationExt, SyntaxNodeCast};
declare_rule! {
/// Disallow unused variables.
@@ -277,4 +280,24 @@ impl Rule for NoUnusedVariables {
Some(diag)
}
+
+ fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
+ let node = ctx.query();
+ let mut mutation = ctx.root().begin();
+ let name = node.name_token().ok()?;
+ let name_trimmed = name.text_trimmed();
+ let new_text_trimmed = format!("_{}", name_trimmed);
+ mutation.replace_node(
+ node.clone(),
+ js_identifier_binding(ident(&new_text_trimmed)),
+ );
+
+ Some(JsRuleAction {
+ mutation,
+ category: ActionCategory::QuickFix,
+ applicability: Applicability::MaybeIncorrect,
+ message: markup! { "If this is intentional, prepend "<Emphasis>{name_trimmed}</Emphasis>" with an underscore." }
+ .to_owned(),
+ })
+ }
}

MODIFY
crates/rome_js_analyze/tests/specs/nursery/noUnusedVariables/noUnusedVariables.js
crates/rome_js_analyze/tests/specs/nursery/noUnusedVariables/noUnusedVariables.js
@@ -54,3 +54,16 @@ console.log(<Button att={value}/>);
new (class C {
})
+
+(function loreum(hey, ai) {
+ console.log(ai);
+})();
+
+const a = {
+ loreum(a,b) {
+ console.log(b)
+ }
+};
+a;
+
+

MODIFY
website/package.json
website/package.json
"start": "npm-run-all --parallel watch:** ",
"watch:eleventy": "eleventy --serve",
"watch:sass": "sass --style=compressed src/styles:src/_includes/styles --watch",
- "format": "cargo rome-cli-dev format --write ."
+ "format": "cargo rome-cli-dev format --write .",
+ "check": "cd ../ && cargo rome-cli-dev check ./website/src"
},
"devDependencies": {
"@types/node": "^18.6.1",

fix(rome_js_analyze): add code action for `noUnusedVariables` (#3534)