oxc/crates/oxc_regular_expression/examples/regex_visitor.rs
leaysgur 5a73a663dc refactor(regular_expression)!: Simplify public APIs (#6262)
This PR makes 2 changes to improve the existing API that are not very useful.

- Remove `(Literal)Parser` and `FlagsParser` and their ASTs
- Add `with_flags(flags_text)` helper to `ParserOptions`

Here are the details.

> Remove `(Literal)Parser` and `FlagsParser` and their ASTs

Previously, the `oxc_regular_expression` crate exposed 3 parsers.

- `(Literal)Parser`: assumes `/pattern/flags` format
- `PatternParser`: assumes `pattern` part only
- `FlagsParser`: assumes `flags` part only

However, it turns out that in actual usecases, only the `PatternParser` is actually sufficient, as the pattern and flags are validated and sliced in advance on the `oxc_parser` side.

The current usecase for `(Literal)Parser` is mostly for internal testing.

There were also some misuses of `(Literal)Parser` that restore `format!("/{pattern}/{flags}")` back and use `(Literal)Parser`.

Therefore, only `PatternParser` is now published, and unnecessary ASTs have been removed.
(This also obsoletes #5592 .)

> Added `with_flags(flags_text)` helper to `ParserOptions`

Strictly speaking, there was a subtle difference between the "flag" strings that users were aware of and the "mode" recognised by the parser.

Therefore, it was a common mistake to forget to enable `unicode_mode` when using the `v` flag.

With this helper, crate users no longer need to distinguish between flags and modes.
2024-10-03 02:47:08 +00:00

31 lines
893 B
Rust

#![allow(clippy::print_stdout)]
use oxc_allocator::Allocator;
use oxc_regular_expression::{
visit::{RegExpAstKind, Visit},
Parser, ParserOptions,
};
use oxc_span::GetSpan;
struct TestVisitor;
impl Visit<'_> for TestVisitor {
fn enter_node(&mut self, kind: RegExpAstKind) {
println!("enter_node: {:?} {kind:?}", kind.span());
}
fn leave_node(&mut self, kind: RegExpAstKind) {
println!("leave_node: {:?} {kind:?}", kind.span());
}
}
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();
let mut visitor = TestVisitor;
visitor.visit_pattern(&pattern);
}