Skip to content

Commit

Permalink
refactor(linter): Use parsed patterns for `unicorn/prefer-string-repl…
Browse files Browse the repository at this point in the history
…ace-all` rule (#5943)

- part of #5416

Replaces the `is_simple_string` method with a more robust check against the parsed terms from the regular expression.
  • Loading branch information
camchenry committed Sep 21, 2024
1 parent c477424 commit 3273b64
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions crates/oxc_linter/src/rules/unicorn/prefer_string_replace_all.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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]
Expand Down

0 comments on commit 3273b64

Please sign in to comment.