From 3273b64a0f73f7ebb4e3856dedbaa33081787e94 Mon Sep 17 00:00:00 2001 From: camchenry <1514176+camchenry@users.noreply.github.com> Date: Sat, 21 Sep 2024 18:02:59 +0000 Subject: [PATCH] refactor(linter): Use parsed patterns for `unicorn/prefer-string-replace-all` rule (#5943) - part of https://github.com/oxc-project/oxc/issues/5416 Replaces the `is_simple_string` method with a more robust check against the parsed terms from the regular expression. --- .../unicorn/prefer_string_replace_all.rs | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/crates/oxc_linter/src/rules/unicorn/prefer_string_replace_all.rs b/crates/oxc_linter/src/rules/unicorn/prefer_string_replace_all.rs index 4452be095..676d2e33c 100644 --- a/crates/oxc_linter/src/rules/unicorn/prefer_string_replace_all.rs +++ b/crates/oxc_linter/src/rules/unicorn/prefer_string_replace_all.rs @@ -4,6 +4,7 @@ use oxc_ast::{ }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; +use oxc_regular_expression::ast::Term; use oxc_span::{CompactStr, GetSpan, Span}; use crate::{ast_util::extract_regex_flags, context::LintContext, rule::Rule, AstNode}; @@ -125,18 +126,21 @@ fn get_pattern_replacement<'a>( return None; } - let pattern_text = reg_exp_literal.regex.pattern.source_text(ctx.source_text()); - let pattern_text = pattern_text.as_ref(); - if !is_simple_string(pattern_text) { + let pattern_terms = reg_exp_literal + .regex + .pattern + .as_pattern() + .and_then(|pattern| pattern.body.body.first().map(|it| &it.body))?; + let is_simple_string = pattern_terms.iter().all(|term| matches!(term, Term::Character(_))); + + if !is_simple_string { return None; } - Some(CompactStr::new(pattern_text)) -} + let pattern_text = reg_exp_literal.regex.pattern.source_text(ctx.source_text()); + let pattern_text = pattern_text.as_ref(); -fn is_simple_string(str: &str) -> bool { - str.chars() - .all(|c| !matches!(c, '^' | '$' | '+' | '[' | '{' | '(' | '\\' | '.' | '?' | '*' | '|')) + Some(CompactStr::new(pattern_text)) } #[test]