Skip to content
This repository was archived by the owner on Aug 31, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/rome_diagnostics_categories/src/categories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ define_dategories! {
"lint/nursery/useIframeTitle": "https://docs.rome.tools/lint/rules/useIframeTitle",
"lint/nursery/useNumericLiterals": "https://docs.rome.tools/lint/rules/useNumericLiterals",
"lint/nursery/noNoninteractiveElementToInteractiveRole": "https://docs.rome.tools/lint/rules/noNoninteractiveElementToInteractiveRole",
"lint/nursery/noUselessRename": "https://docs.rome.tools/lint/rules/noUselessRename",
"lint/nursery/useValidForDirection": "https://docs.rome.tools/lint/rules/useValidForDirection",
"lint/nursery/useHookAtTopLevel": "https://docs.rome.tools/lint/rules/useHookAtTopLevel",
"lint/nursery/noDuplicateJsxProps": "https://docs.rome.tools/lint/rules/noDuplicateJsxProps",
Expand Down
3 changes: 2 additions & 1 deletion crates/rome_js_analyze/src/analyzers/nursery.rs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

180 changes: 180 additions & 0 deletions crates/rome_js_analyze/src/analyzers/nursery/no_useless_rename.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
JsExportNamedFromSpecifier, JsExportNamedSpecifier, JsNamedImportSpecifier,
JsObjectBindingPatternProperty, JsSyntaxElement,
};
use rome_rowan::{declare_node_union, AstNode, BatchMutationExt};

use crate::JsRuleAction;

declare_rule! {
/// Disallow renaming import, export, and destructured assignments to the same name.
///
/// ES2015 allows for the renaming of references in import and export statements as well as destructuring assignments.
/// This gives programmers a concise syntax for performing these operations while renaming these references:
///
/// ```js
/// import { foo as bar } from "baz";
/// export { foo as bar };
/// let { foo: bar } = baz;
/// ```
///
/// With this syntax, it is possible to rename a reference to the same name.
/// This is a completely redundant operation, as this is the same as not renaming at all.
///
/// Source: https://eslint.org/docs/latest/rules/no-useless-rename
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// import { foo as foo } from "bar";
/// ```
///
/// ```js,expect_diagnostic
/// export { foo as foo };
/// ```
///
/// ```js,expect_diagnostic
/// let { foo: foo } = bar;
/// ```
///
/// ### Valid
///
/// ```js
/// import { foo as bar } from "baz";
/// ```
///
/// ```js
/// export { foo as bar };
/// ```
///
/// ```js
/// let { foo: bar } = baz;
/// ```
///
pub(crate) NoUselessRename {
version: "next",
name: "noUselessRename",
recommended: true,
}
}

declare_node_union! {
pub(crate) JsRenaming = JsExportNamedFromSpecifier | JsExportNamedSpecifier | JsNamedImportSpecifier | JsObjectBindingPatternProperty
}

impl Rule for NoUselessRename {
type Query = Ast<JsRenaming>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();

fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let renaming = ctx.query();
let (old_name, new_name) = match renaming {
JsRenaming::JsExportNamedFromSpecifier(x) => (
x.source_name().ok()?.value().ok()?,
x.export_as()?.exported_name().ok()?.value().ok()?,
),
JsRenaming::JsExportNamedSpecifier(x) => (
x.local_name().ok()?.value_token().ok()?,
x.exported_name().ok()?.value().ok()?,
),
JsRenaming::JsNamedImportSpecifier(x) => (
x.name().ok()?.value().ok()?,
x.local_name()
.ok()?
.as_js_identifier_binding()?
.name_token()
.ok()?,
),
JsRenaming::JsObjectBindingPatternProperty(x) => (
x.member().ok()?.as_js_literal_member_name()?.value().ok()?,
x.pattern()
.ok()?
.as_any_js_binding()?
.as_js_identifier_binding()?
.name_token()
.ok()?,
),
};
Comment on lines +80 to +106
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this is not something specific to this rule but a pattern we could apply in general to avoid the number of ok() calls necessary in lint rules.

The idea would be to introduce a new function that returns a Result instead of an Option:

fn run(ctx: &RuleContext<Self>) -> Self::Signals {
  Self::is_useless_rename(ctx).ok()
}

fn is_useless_rename(ctx) -> SyntaxResult<bool> {
	// existing code but without any `ok` call
}

Copy link
Contributor Author

@Conaclos Conaclos Dec 30, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue is that some calls return an option. e.g. x.export_as()? or .as_js_identifier_binding()?. I can use an if statement and return an early Ok(false). However I am not sure if it is worth it?

Copy link
Contributor

@ematipico ematipico Jan 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went down that road, and the APIs are good like this. Because some APIs return Option, trying to fit them inside a function that returns Result makes everything weird and doesn't feel right.

(old_name.text_trimmed() == new_name.text_trimmed()).then_some(())
}

fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let renaming = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
renaming.syntax().text_trimmed_range(),
markup! {
"Useless rename."
},
))
}

fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let renaming = ctx.query();
let mut mutation = ctx.root().begin();
match renaming {
JsRenaming::JsExportNamedFromSpecifier(x) => {
let last_token = x.source_name().ok()?.value().ok()?;
let export_as = x.export_as()?;
let export_as_last_token = export_as.exported_name().ok()?.value().ok()?;
let replacing_token = last_token.with_trailing_trivia_pieces(
last_token
.trailing_trivia()
.pieces()
.chain(
export_as_last_token
.trailing_trivia()
.pieces()
.skip_while(|p| p.is_newline() || p.is_whitespace()),
)
.collect::<Vec<_>>(),
);
mutation.remove_node(export_as);
mutation.replace_token_discard_trivia(last_token, replacing_token);
}
JsRenaming::JsExportNamedSpecifier(x) => {
let replacing =
make::js_export_named_shorthand_specifier(x.local_name().ok()?).build();
mutation.replace_element(
JsSyntaxElement::Node(x.syntax().clone()),
JsSyntaxElement::Node(replacing.syntax().clone()),
);
}
JsRenaming::JsNamedImportSpecifier(x) => {
let replacing =
make::js_shorthand_named_import_specifier(x.local_name().ok()?).build();
mutation.replace_element(
JsSyntaxElement::Node(x.syntax().clone()),
JsSyntaxElement::Node(replacing.syntax().clone()),
);
}
JsRenaming::JsObjectBindingPatternProperty(x) => {
let mut replacing_builder = make::js_object_binding_pattern_shorthand_property(
x.pattern().ok()?.as_any_js_binding()?.clone(),
);
if let Some(init) = x.init() {
replacing_builder = replacing_builder.with_init(init);
}
mutation.replace_element(
JsSyntaxElement::Node(x.syntax().clone()),
JsSyntaxElement::Node(replacing_builder.build().syntax().clone()),
);
}
}
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! { "Remove the renaming." }.to_owned(),
mutation,
})
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
let { /*before*/ foo: foo /*after*/ } = obj;

let { a, foo: foo } = obj;

let { foo: foo, b } = obj;

let {
foo: { bar: bar },
} = obj;

let { /*before*/ foo: foo /*after*/ = /*before default*/ a /*after default*/ } =
obj;

function f({ foo: foo }) {}

({ foo: foo }) => {};

import { /*before*/ foo as foo /*after*/ } from "foo";

import { a as a } from "foo";

export { /*before*/ foo as foo /*after*/ };

export { /*before*/ foo as foo /*after*/ } from "foo";

// following cases are supported by ESLint

//import {a as \u0061} from 'foo';
//import {\u0061 as a} from 'foo';
//export {\u0061 as a};
//export {a as \u0061};

//let {"a": a} = obj;
//import { "a" as a}
//export { a as "a"}
Loading