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

feat(regular_expression): add terms visitor to pattern #5951

Closed
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
61 changes: 61 additions & 0 deletions crates/oxc_regular_expression/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,3 +370,64 @@ pub struct NamedReference<'a> {
pub span: Span,
pub name: Atom<'a>,
}

impl Pattern<'_> {
/// Calls the given closure on every [`Term`] in the [`Pattern`].
///
/// ## Example
/// ```rust
/// use oxc_allocator::Allocator;
/// use oxc_regular_expression::{Parser, ParserOptions};
///
/// let allocator = Allocator::default();
/// let parser = Parser::new(&allocator, r"/a|b+|c/i", ParserOptions::default());
/// let regex = parser.parse().unwrap();
///
/// regex.pattern.visit_terms(&mut |term| {
/// dbg!(term);
/// });
/// ```
pub fn visit_terms<'a, F: FnMut(&'a Term<'a>)>(&'a self, f: &mut F) {
self.visit_terms_disjunction(&self.body, f);
}

/// Calls the given closure on every [`Term`] in the [`Disjunction`].
fn visit_terms_disjunction<'a, F: FnMut(&'a Term<'a>)>(
&'a self,
disjunction: &'a Disjunction,
f: &mut F,
) {
for alternative in &disjunction.body {
self.visit_terms_alternative(alternative, f);
}
}

/// Calls the given closure on every [`Term`] in the [`Alternative`].
fn visit_terms_alternative<'a, F: FnMut(&'a Term<'a>)>(
&'a self,
alternative: &'a Alternative,
f: &mut F,
) {
for term in &alternative.body {
match term {
Term::LookAroundAssertion(lookaround) => {
f(term);
self.visit_terms_disjunction(&lookaround.body, f);
}
Term::Quantifier(quant) => {
f(term);
f(&quant.body);
}
Term::CapturingGroup(group) => {
f(term);
self.visit_terms_disjunction(&group.body, f);
}
Term::IgnoreGroup(group) => {
f(term);
self.visit_terms_disjunction(&group.body, f);
}
_ => f(term),
}
}
}
}