This repository has been archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 656
feat(rome_js_analyze): noAccumulatingSpread #4426
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
1e16a58
feat(rome_js_analyze): noAccumulatingSpread
Vivalldi e98c66b
get a super general condition working
Vivalldi d511e02
all my cases pass as expected
Vivalldi ccf3332
make analyzer semantic
Vivalldi 14b8ba2
move rule & run codegen
Vivalldi 1986953
nicer tests
Vivalldi 83fe08a
tidy doc string
Vivalldi 714cb6b
update changelog
Vivalldi 9a10db3
update example
Vivalldi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
122 changes: 122 additions & 0 deletions
122
crates/rome_js_analyze/src/semantic_analyzers/nursery/no_accumulating_spread.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic}; | ||
use rome_console::markup; | ||
use rome_js_semantic::SemanticModel; | ||
use rome_js_syntax::{ | ||
AnyJsFunction, JsCallArgumentList, JsCallArguments, JsCallExpression, JsFormalParameter, | ||
JsParameterList, JsParameters, JsSpread, | ||
}; | ||
use rome_rowan::AstNode; | ||
|
||
use crate::semantic_services::Semantic; | ||
|
||
declare_rule! { | ||
/// Disallow the use of spread (`...`) syntax on accumulators. | ||
/// | ||
/// Spread syntax allows an iterable to be expanded into its individual elements. | ||
/// | ||
/// Spread syntax should be avoided on accumulators (like those in `.reduce`) | ||
/// because it causes a time complexity of `O(n^2)` instead of `O(n)`. | ||
/// | ||
/// Source: https://prateeksurana.me/blog/why-using-object-spread-with-reduce-bad-idea/ | ||
/// | ||
/// ## Examples | ||
/// | ||
/// ### Invalid | ||
/// | ||
/// ```js,expect_diagnostic | ||
/// var a = ['a', 'b', 'c']; | ||
/// a.reduce((acc, val) => [...acc, val], []); | ||
/// ``` | ||
/// | ||
/// ```js,expect_diagnostic | ||
/// var a = ['a', 'b', 'c']; | ||
/// a.reduce((acc, val) => {return [...acc, val];}, []); | ||
/// ``` | ||
/// | ||
/// ```js,expect_diagnostic | ||
/// var a = ['a', 'b', 'c']; | ||
/// a.reduce((acc, val) => ({...acc, [val]: val}), {}); | ||
/// ``` | ||
/// | ||
/// ## Valid | ||
/// | ||
/// ```js | ||
/// var a = ['a', 'b', 'c']; | ||
/// a.reduce((acc, val) => {acc.push(val); return acc}, []); | ||
/// ``` | ||
/// | ||
pub(crate) NoAccumulatingSpread { | ||
version: "next", | ||
name: "noAccumulatingSpread", | ||
recommended: false, | ||
} | ||
} | ||
|
||
impl Rule for NoAccumulatingSpread { | ||
type Query = Semantic<JsSpread>; | ||
type State = (); | ||
type Signals = Option<Self::State>; | ||
type Options = (); | ||
|
||
fn run(ctx: &RuleContext<Self>) -> Self::Signals { | ||
let node = ctx.query(); | ||
let model = ctx.model(); | ||
|
||
is_known_accumulator(node, model)?.then_some(()) | ||
} | ||
|
||
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> { | ||
let node = ctx.query(); | ||
Some( | ||
RuleDiagnostic::new( | ||
rule_category!(), | ||
node.range(), | ||
markup! { | ||
"Avoid the use of spread (`...`) syntax on accumulators." | ||
}, | ||
) | ||
.note(markup! { | ||
"Spread syntax should be avoided on accumulators (like those in `.reduce`) because it causes a time complexity of `O(n^2)`." | ||
}), | ||
) | ||
} | ||
} | ||
|
||
fn is_known_accumulator(node: &JsSpread, model: &SemanticModel) -> Option<bool> { | ||
let reference = node | ||
.argument() | ||
.ok()? | ||
.as_js_identifier_expression()? | ||
.name() | ||
.ok()?; | ||
|
||
let parameter = model | ||
.binding(&reference) | ||
.and_then(|declaration| declaration.syntax().parent()) | ||
.and_then(JsFormalParameter::cast)?; | ||
let function = parameter | ||
.parent::<JsParameterList>() | ||
.and_then(|list| list.parent::<JsParameters>()) | ||
.and_then(|parameters| parameters.parent::<AnyJsFunction>())?; | ||
let call_expression = function | ||
.parent::<JsCallArgumentList>() | ||
.and_then(|arguments| arguments.parent::<JsCallArguments>()) | ||
.and_then(|arguments| arguments.parent::<JsCallExpression>())?; | ||
|
||
let name = call_expression | ||
.callee() | ||
.ok()? | ||
.as_js_static_member_expression()? | ||
.member() | ||
.ok()? | ||
.as_js_name()? | ||
.value_token() | ||
.ok()?; | ||
let name = name.text_trimmed(); | ||
|
||
if matches!(name, "reduce" | "reduceRight") { | ||
Some(parameter.syntax().index() == 0) | ||
} else { | ||
None | ||
} | ||
} |
33 changes: 33 additions & 0 deletions
33
crates/rome_js_analyze/tests/specs/nursery/noAccumulatingSpread/invalid.jsonc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
[ | ||
// Array - Arrow return | ||
"foo.reduce((acc, bar) => [...acc, bar], [])", | ||
"foo.reduceRight((acc, bar) => [...acc, bar], [])", | ||
|
||
// Array - Body return | ||
"foo.reduce((acc, bar) => {return [...acc, bar];}, [])", | ||
"foo.reduceRight((acc, bar) => {return [...acc, bar];}, [])", | ||
|
||
// Array - Arrow return with item spread | ||
"foo.reduce((acc, bar) => [...acc, ...bar], [])", | ||
"foo.reduceRight((acc, bar) => [...acc, ...bar], [])", | ||
|
||
// Array - Body return with item spread | ||
"foo.reduce((acc, bar) => {return [...acc, ...bar];}, [])", | ||
"foo.reduceRight((acc, bar) => {return [...acc, ...bar];}, [])", | ||
|
||
// Object - Arrow return | ||
"foo.reduce((acc, bar) => ({...acc, [bar.key]: bar.value}), {})", | ||
"foo.reduceRight((acc, bar) => ({...acc, [bar.key]: bar.value}), {})", | ||
|
||
// Object - Body return | ||
"foo.reduce((acc, bar) => {return {...acc, [bar.key]: bar.value};}, {})", | ||
"foo.reduceRight((acc, bar) => {return {...acc, [bar.key]: bar.value};}, {})", | ||
|
||
// Object - Arrow return with item spread | ||
"foo.reduce((acc, bar) => ({...acc, ...bar}), {})", | ||
"foo.reduceRight((acc, bar) => ({...acc, ...bar}), {})", | ||
|
||
// Object - Body return with item spread | ||
"foo.reduce((acc, bar) => {return {...acc, ...bar};}, {})", | ||
"foo.reduceRight((acc, bar) => {return {...acc, ...bar};}, {})" | ||
] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we add an example where
.reduce
is not a built-in function? For example: