Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/big-shoes-know.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@biomejs/biome": patch
---

Added the nursery rule [`useRegexpExec`](https://biomejs.dev/linter/rules/use-regexp-exec/). Enforce `RegExp#exec` over `String#match` if no global flag is provided.
2 changes: 1 addition & 1 deletion crates/biome_analyze/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -893,7 +893,7 @@ impl Rule for ForLoopCountReferences {
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();

// The model holds all informations about the semantic, like scopes and declarations
// The model holds all information about the semantic, like scopes and declarations
let model = ctx.model();

// Here we are extracting the `let i = 0;` declaration in for loop
Expand Down
24 changes: 24 additions & 0 deletions crates/biome_cli/src/execute/migrate/eslint_any_rule_to_biome.rs

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

77 changes: 49 additions & 28 deletions crates/biome_configuration/src/analyzer/linter/rules.rs

Large diffs are not rendered by default.

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

1 change: 1 addition & 0 deletions crates/biome_diagnostics_categories/src/categories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ define_categories! {
"lint/nursery/useMaxParams": "https://biomejs.dev/linter/rules/use-max-params",
"lint/nursery/useQwikMethodUsage": "https://biomejs.dev/linter/rules/use-qwik-method-usage",
"lint/nursery/useQwikValidLexicalScope": "https://biomejs.dev/linter/rules/use-qwik-valid-lexical-scope",
"lint/nursery/useRegexpExec": "https://biomejs.dev/linter/rules/use-regexp-exec",
"lint/nursery/useSortedClasses": "https://biomejs.dev/linter/rules/use-sorted-classes",
"lint/nursery/useSpread": "https://biomejs.dev/linter/rules/no-spread",
"lint/nursery/useUniqueGraphqlOperationName": "https://biomejs.dev/linter/rules/use-unique-graphql-operation-name",
Expand Down
3 changes: 2 additions & 1 deletion crates/biome_js_analyze/src/lint/nursery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ pub mod use_find;
pub mod use_max_params;
pub mod use_qwik_method_usage;
pub mod use_qwik_valid_lexical_scope;
pub mod use_regexp_exec;
pub mod use_sorted_classes;
pub mod use_spread;
pub mod use_vue_define_macros_order;
pub mod use_vue_multi_word_component_names;
declare_lint_group! { pub Nursery { name : "nursery" , rules : [self :: no_continue :: NoContinue , self :: no_deprecated_imports :: NoDeprecatedImports , self :: no_duplicated_spread_props :: NoDuplicatedSpreadProps , self :: no_empty_source :: NoEmptySource , self :: no_equals_to_null :: NoEqualsToNull , self :: no_floating_promises :: NoFloatingPromises , self :: no_for_in :: NoForIn , self :: no_import_cycles :: NoImportCycles , self :: no_increment_decrement :: NoIncrementDecrement , self :: no_jsx_literals :: NoJsxLiterals , self :: no_leaked_render :: NoLeakedRender , self :: no_misused_promises :: NoMisusedPromises , self :: no_multi_str :: NoMultiStr , self :: no_next_async_client_component :: NoNextAsyncClientComponent , self :: no_parameters_only_used_in_recursion :: NoParametersOnlyUsedInRecursion , self :: no_proto :: NoProto , self :: no_react_forward_ref :: NoReactForwardRef , self :: no_shadow :: NoShadow , self :: no_sync_scripts :: NoSyncScripts , self :: no_ternary :: NoTernary , self :: no_unknown_attribute :: NoUnknownAttribute , self :: no_unnecessary_conditions :: NoUnnecessaryConditions , self :: no_unresolved_imports :: NoUnresolvedImports , self :: no_unused_expressions :: NoUnusedExpressions , self :: no_useless_catch_binding :: NoUselessCatchBinding , self :: no_useless_undefined :: NoUselessUndefined , self :: no_vue_data_object_declaration :: NoVueDataObjectDeclaration , self :: no_vue_duplicate_keys :: NoVueDuplicateKeys , self :: no_vue_reserved_keys :: NoVueReservedKeys , self :: no_vue_reserved_props :: NoVueReservedProps , self :: use_array_sort_compare :: UseArraySortCompare , self :: use_consistent_arrow_return :: UseConsistentArrowReturn , self :: use_exhaustive_switch_cases :: UseExhaustiveSwitchCases , self :: use_explicit_type :: UseExplicitType , self :: use_find :: UseFind , self :: use_max_params :: UseMaxParams , self :: use_qwik_method_usage :: UseQwikMethodUsage , self :: use_qwik_valid_lexical_scope :: UseQwikValidLexicalScope , self :: use_sorted_classes :: UseSortedClasses , self :: use_spread :: UseSpread , self :: use_vue_define_macros_order :: UseVueDefineMacrosOrder , self :: use_vue_multi_word_component_names :: UseVueMultiWordComponentNames ,] } }
declare_lint_group! { pub Nursery { name : "nursery" , rules : [self :: no_continue :: NoContinue , self :: no_deprecated_imports :: NoDeprecatedImports , self :: no_duplicated_spread_props :: NoDuplicatedSpreadProps , self :: no_empty_source :: NoEmptySource , self :: no_equals_to_null :: NoEqualsToNull , self :: no_floating_promises :: NoFloatingPromises , self :: no_for_in :: NoForIn , self :: no_import_cycles :: NoImportCycles , self :: no_increment_decrement :: NoIncrementDecrement , self :: no_jsx_literals :: NoJsxLiterals , self :: no_leaked_render :: NoLeakedRender , self :: no_misused_promises :: NoMisusedPromises , self :: no_multi_str :: NoMultiStr , self :: no_next_async_client_component :: NoNextAsyncClientComponent , self :: no_parameters_only_used_in_recursion :: NoParametersOnlyUsedInRecursion , self :: no_proto :: NoProto , self :: no_react_forward_ref :: NoReactForwardRef , self :: no_shadow :: NoShadow , self :: no_sync_scripts :: NoSyncScripts , self :: no_ternary :: NoTernary , self :: no_unknown_attribute :: NoUnknownAttribute , self :: no_unnecessary_conditions :: NoUnnecessaryConditions , self :: no_unresolved_imports :: NoUnresolvedImports , self :: no_unused_expressions :: NoUnusedExpressions , self :: no_useless_catch_binding :: NoUselessCatchBinding , self :: no_useless_undefined :: NoUselessUndefined , self :: no_vue_data_object_declaration :: NoVueDataObjectDeclaration , self :: no_vue_duplicate_keys :: NoVueDuplicateKeys , self :: no_vue_reserved_keys :: NoVueReservedKeys , self :: no_vue_reserved_props :: NoVueReservedProps , self :: use_array_sort_compare :: UseArraySortCompare , self :: use_consistent_arrow_return :: UseConsistentArrowReturn , self :: use_exhaustive_switch_cases :: UseExhaustiveSwitchCases , self :: use_explicit_type :: UseExplicitType , self :: use_find :: UseFind , self :: use_max_params :: UseMaxParams , self :: use_qwik_method_usage :: UseQwikMethodUsage , self :: use_qwik_valid_lexical_scope :: UseQwikValidLexicalScope , self :: use_regexp_exec :: UseRegexpExec , self :: use_sorted_classes :: UseSortedClasses , self :: use_spread :: UseSpread , self :: use_vue_define_macros_order :: UseVueDefineMacrosOrder , self :: use_vue_multi_word_component_names :: UseVueMultiWordComponentNames ,] } }
106 changes: 106 additions & 0 deletions crates/biome_js_analyze/src/lint/nursery/use_regexp_exec.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
use crate::services::typed::Typed;
use biome_analyze::{
Rule, RuleDiagnostic, RuleDomain, RuleSource, context::RuleContext, declare_lint_rule,
};
use biome_console::markup;
use biome_js_syntax::JsCallExpression;
use biome_js_type_info::{Literal, ResolvedTypeData, TypeData};
use biome_rowan::{AstNode, AstSeparatedList};
use biome_rule_options::use_regexp_exec::UseRegexpExecOptions;

declare_lint_rule! {
/// Enforce `RegExp#exec` over `String#match` if no global flag is provided.
///
/// String#match is defined to work the same as RegExp#exec when the regular expression does not include the g flag.
/// Keeping to consistently using one of the two can help improve code readability.
///
/// RegExp#exec may also be slightly faster than String#match; this is the reason to choose it as the preferred usage.
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,file=invalid.ts,expect_diagnostic
/// 'something'.match(/thing/);
/// ```
///
/// ### Valid
///
/// ```ts,file=valid.ts
/// /thing/.exec('something');
/// ```
///
pub UseRegexpExec {
version: "next",
name: "useRegexpExec",
language: "js",
recommended: false,
sources: &[RuleSource::EslintTypeScript("prefer-regexp-exec").same(), RuleSource::EslintRegexp("prefer-regexp-exec").same()],
Copy link
Contributor

Choose a reason for hiding this comment

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

Are these two sources implementing the exact same rule? Otherwise, maybe one or both need to be changed from same() to inspired().

Copy link
Member Author

Choose a reason for hiding this comment

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

They are exactly the same

domains: &[RuleDomain::Project],
}
}

impl Rule for UseRegexpExec {
type Query = Typed<JsCallExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = UseRegexpExecOptions;

fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();

let binding = node.callee().ok()?.omit_parentheses();
let callee = binding.as_js_static_member_expression()?;

let call_object = callee.object().ok()?;
if !ctx
.type_of_expression(&call_object)
.is_string_or_string_literal()
{
return None;
}

let call_name = callee.member().ok()?.as_js_name()?.to_trimmed_text();
if call_name != "match" {
return None;
}

let args = node.arguments().ok()?.args();
let first_arg = args.first()?.ok()?;
let express = first_arg.as_any_js_expression()?;

let value_type = ctx.type_of_expression(express);

if value_type
.resolved_data()
.map(ResolvedTypeData::as_raw_data)
.is_some_and(|ty| match ty {
TypeData::Literal(literal) => match literal.as_ref() {
Literal::RegExp(literal) => !literal.flags.contains('g'),
_ => false,
},
_ => false,
})
{
return Some(());
}

None
}

fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Prefer "<Emphasis>"RegExp#exec()"</Emphasis>" over "<Emphasis>"String#match()"</Emphasis>" when searching within a string."
},
)
.note(markup! {
"Use "<Emphasis>"RegExp#exec()"</Emphasis>" instead of "<Emphasis>"String#match()"</Emphasis>" for consistent and slightly faster regex matching."
}),
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'something'.match(/thing/);

'some things are just things'.match(/thing/);

'something'.match(new RegExp(/thing/));

const text = 'something';
const search = /thing/;
text.match(search);

const text1 = 'something';
const search1 = new RegExp(/thing/);
text1.match(search1);
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
source: crates/biome_js_analyze/tests/spec_tests.rs
expression: invalid.js
---
# Input
```js
'something'.match(/thing/);

'some things are just things'.match(/thing/);

'something'.match(new RegExp(/thing/));

const text = 'something';
const search = /thing/;
text.match(search);

const text1 = 'something';
const search1 = new RegExp(/thing/);
text1.match(search1);

```

# Diagnostics
```
invalid.js:1:1 lint/nursery/useRegexpExec ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

i Prefer RegExp#exec() over String#match() when searching within a string.

> 1 │ 'something'.match(/thing/);
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^
2 │
3 │ 'some things are just things'.match(/thing/);

i Use RegExp#exec() instead of String#match() for consistent and slightly faster regex matching.


```

```
invalid.js:3:1 lint/nursery/useRegexpExec ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

i Prefer RegExp#exec() over String#match() when searching within a string.

1 │ 'something'.match(/thing/);
2 │
> 3 │ 'some things are just things'.match(/thing/);
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4 │
5 │ 'something'.match(new RegExp(/thing/));

i Use RegExp#exec() instead of String#match() for consistent and slightly faster regex matching.


```

```
invalid.js:9:1 lint/nursery/useRegexpExec ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

i Prefer RegExp#exec() over String#match() when searching within a string.

7 │ const text = 'something';
8 │ const search = /thing/;
> 9 │ text.match(search);
│ ^^^^^^^^^^^^^^^^^^
10 │
11 │ const text1 = 'something';

i Use RegExp#exec() instead of String#match() for consistent and slightly faster regex matching.


```
22 changes: 22 additions & 0 deletions crates/biome_js_analyze/tests/specs/nursery/useRegexpExec/valid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/* should not generate diagnostics */
/thing/.exec('something');

'some things are just things'.match(/thing/g);

const text = 'something';
const search = /thing/;
search.exec(text);

const text1 = 'something';
const search1 = /thing/g;
text1.match(search1);

const obj = {
match: () => { }
}
obj.match(/thing/)

new RegExp(/thing/).exec('something');

'some things are just things'.match(new RegExp(/thing/g));
'some things are just things'.match(new RegExp(/thing/, "g"));
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
---
source: crates/biome_js_analyze/tests/spec_tests.rs
expression: valid.js
---
# Input
```js
/* should not generate diagnostics */
/thing/.exec('something');

'some things are just things'.match(/thing/g);

const text = 'something';
const search = /thing/;
search.exec(text);

const text1 = 'something';
const search1 = /thing/g;
text1.match(search1);

const obj = {
match: () => { }
}
obj.match(/thing/)

new RegExp(/thing/).exec('something');

'some things are just things'.match(new RegExp(/thing/g));
'some things are just things'.match(new RegExp(/thing/, "g"));

```
1 change: 1 addition & 0 deletions crates/biome_rule_options/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,7 @@ pub mod use_qwik_valid_lexical_scope;
pub mod use_react_function_components;
pub mod use_readonly_class_properties;
pub mod use_regex_literals;
pub mod use_regexp_exec;
pub mod use_self_closing_elements;
pub mod use_semantic_elements;
pub mod use_shorthand_assign;
Expand Down
6 changes: 6 additions & 0 deletions crates/biome_rule_options/src/use_regexp_exec.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
use biome_deserialize_macros::{Deserializable, Merge};
use serde::{Deserialize, Serialize};
#[derive(Default, Clone, Debug, Deserialize, Deserializable, Eq, Merge, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields, default)]
pub struct UseRegexpExecOptions {}
14 changes: 14 additions & 0 deletions packages/@biomejs/backend-jsonrpc/src/workspace.ts

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

Loading