Skip to content

Commit

Permalink
refactor(linter/no-control-regex): remove duplicate code
Browse files Browse the repository at this point in the history
  • Loading branch information
DonIsaac committed Oct 13, 2024
1 parent 97c8a36 commit 74d1afd
Showing 1 changed file with 24 additions and 36 deletions.
60 changes: 24 additions & 36 deletions crates/oxc_linter/src/rules/eslint/no_control_regex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,24 +88,7 @@ impl Rule for NoControlRegex {
if let Argument::StringLiteral(pattern) = &expr.arguments[0] {
// get pattern from arguments. Missing or non-string arguments
// will be runtime errors, but are not covered by this rule.
let alloc = Allocator::default();
let flags = extract_regex_flags(&expr.arguments);
let flags_text = flags.map_or(String::new(), |f| f.to_string());
let parser = Parser::new(
&alloc,
pattern.value.as_str(),
ParserOptions::default()
.with_span_offset(
expr.arguments.first().map_or(0, |arg| arg.span().start),
)
.with_flags(&flags_text),
);

let Ok(pattern) = parser.parse() else {
return;
};

check_pattern(context, &pattern, expr.span);
parse_and_check_regex(context, &pattern.value, &expr.arguments, expr.span);
}
}
}
Expand All @@ -123,24 +106,7 @@ impl Rule for NoControlRegex {
if let Argument::StringLiteral(pattern) = &expr.arguments[0] {
// get pattern from arguments. Missing or non-string arguments
// will be runtime errors, but are not covered by this rule.
let alloc = Allocator::default();
let flags = extract_regex_flags(&expr.arguments);
let flags_text = flags.map_or(String::new(), |f| f.to_string());
let parser = Parser::new(
&alloc,
pattern.value.as_str(),
ParserOptions::default()
.with_span_offset(
expr.arguments.first().map_or(0, |arg| arg.span().start),
)
.with_flags(&flags_text),
);

let Ok(pattern) = parser.parse() else {
return;
};

check_pattern(context, &pattern, expr.span);
parse_and_check_regex(context, &pattern.value, &expr.arguments, expr.span);
}
}
}
Expand All @@ -149,6 +115,28 @@ impl Rule for NoControlRegex {
}
}

fn parse_and_check_regex<'a>(
ctx: &LintContext<'a>,
source_text: &'a str,
arguments: &oxc_allocator::Vec<'a, Argument<'a>>,
expr_span: Span,
) {
let allocator = Allocator::default();
let flags = extract_regex_flags(arguments);
let flags_text = flags.map_or(String::new(), |f| f.to_string());
let parser = Parser::new(
&allocator,
source_text,
ParserOptions::default()
.with_span_offset(arguments.first().map_or(0, |arg| arg.span().start))
.with_flags(&flags_text),
);
let Ok(pattern) = parser.parse() else {
return;
};
check_pattern(ctx, &pattern, expr_span);
}

fn check_pattern(context: &LintContext, pattern: &Pattern, span: Span) {
let mut finder = ControlCharacterFinder { control_chars: Vec::new() };
finder.visit_pattern(pattern);
Expand Down

0 comments on commit 74d1afd

Please sign in to comment.