Skip to content

Commit

Permalink
feat(regular_expression): implement visitor pattern trait for regex A…
Browse files Browse the repository at this point in the history
…ST (#6055)

- resolves #5977
- supersedes #5951

To facilitate easier traversal of the Regex AST, this PR defines a `Visit` trait with default implementations that will walk the entirety of the Regex AST. Methods in the `Visit` trait can be overridden with custom implementations to do things like analyzing only certain nodes in a regular expression, which will be useful for regex-related `oxc_linter` rules.

In the future, we should consider automatically generating this code as it is very repetitive, but for now a handwritten visitor is sufficient.
  • Loading branch information
camchenry committed Sep 26, 2024
1 parent 3da3845 commit 7764793
Show file tree
Hide file tree
Showing 3 changed files with 418 additions and 0 deletions.
28 changes: 28 additions & 0 deletions crates/oxc_regular_expression/examples/visitor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#![allow(clippy::print_stdout)]

use oxc_allocator::Allocator;
use oxc_regular_expression::{
visit::{RegExpAstKind, Visit},
Parser, ParserOptions,
};

struct TestVisitor;

impl Visit<'_> for TestVisitor {
fn enter_node(&mut self, kind: RegExpAstKind) {
println!("enter_node: {kind:?}");
}

fn leave_node(&mut self, kind: RegExpAstKind) {
println!("leave_node: {kind:?}");
}
}

fn main() {
let source_text = r"/(https?:\/\/github\.com\/(([^\s]+)\/([^\s]+))\/([^\s]+\/)?(issues|pull)\/([0-9]+))|(([^\s]+)\/([^\s]+))?#([1-9][0-9]*)($|[\s\:\;\-\(\=])/";
let allocator = Allocator::default();
let parser = Parser::new(&allocator, source_text, ParserOptions::default());
let pattern = parser.parse().unwrap().pattern;
let mut visitor = TestVisitor;
visitor.visit_pattern(&pattern);
}
1 change: 1 addition & 0 deletions crates/oxc_regular_expression/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ mod literal_parser;
mod options;
mod span;
mod surrogate_pair;
pub mod visit;

mod generated {
mod derive_clone_in;
Expand Down
Loading

0 comments on commit 7764793

Please sign in to comment.