Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(linter): Use parsed patterns in unicorn/prefer-string-starts-ends-with #5949

Merged
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
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::{BoundaryAssertionKind, Term};
use oxc_span::{GetSpan, Span};

use crate::{
Expand Down Expand Up @@ -146,24 +147,33 @@ fn check_regex(regexp_lit: &RegExpLiteral, pattern_text: &str) -> Option<ErrorKi
return None;
}

if pattern_text.starts_with('^')
&& is_simple_string(&pattern_text[1..regexp_lit.regex.pattern.len()])
{
return Some(ErrorKind::StartsWith);
let alternatives = regexp_lit.regex.pattern.as_pattern().map(|pattern| &pattern.body.body)?;
// Must not be something with multiple alternatives like `/^a|b/`
if alternatives.len() > 1 {
return None;
}
let pattern_terms = alternatives.first().map(|it| &it.body)?;

if pattern_text.ends_with('$')
&& is_simple_string(&pattern_text[0..regexp_lit.regex.pattern.len() - 1])
{
return Some(ErrorKind::EndsWith);
if let Some(Term::BoundaryAssertion(boundary_assert)) = pattern_terms.first() {
if boundary_assert.kind == BoundaryAssertionKind::Start
&& pattern_terms.iter().skip(1).all(|term| matches!(term, Term::Character(_)))
{
return Some(ErrorKind::StartsWith);
}
}

None
}
if let Some(Term::BoundaryAssertion(boundary_assert)) = pattern_terms.last() {
if boundary_assert.kind == BoundaryAssertionKind::End
&& pattern_terms
.iter()
.take(pattern_terms.len() - 1)
.all(|term| matches!(term, Term::Character(_)))
{
return Some(ErrorKind::EndsWith);
}
}

fn is_simple_string(str: &str) -> bool {
str.chars()
.all(|c| !matches!(c, '^' | '$' | '+' | '[' | '{' | '(' | '\\' | '.' | '?' | '*' | '|'))
None
}

// `/^#/i` => `true` (the `i` flag is useless)
Expand Down