Skip to content

Commit

Permalink
feat(regular_expression): add terms visitor to pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
camchenry committed Sep 21, 2024
1 parent 05f592b commit cfb8510
Showing 1 changed file with 61 additions and 0 deletions.
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),
}
}
}
}

0 comments on commit cfb8510

Please sign in to comment.