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.
This commit is contained in:
camchenry 2024-09-21 18:02:59 +00:00
parent c477424bab
commit 3273b64a0f

View file

@ -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]