oxc/crates/oxc_regular_expression/src/options.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

33 lines
1 KiB
Rust

#[derive(Clone, Copy, Debug, Default)]
pub struct ParserOptions {
/// Used to adjust Span positions to fit the global source code.
pub span_offset: u32,
/// Unicode mode(`u` or `v` flag) enabled or not.
pub unicode_mode: bool,
/// Extended Unicode mode(`v` flag) enabled or not.
pub unicode_sets_mode: bool,
// TODO: Add `handle_escape_with_quote_type` like option to support `new RegExp("with \"escape\"")`
}
impl ParserOptions {
#[must_use]
pub fn with_span_offset(self, span_offset: u32) -> Self {
ParserOptions { span_offset, ..self }
}
#[must_use]
pub fn with_flags(self, flags: &str) -> Self {
let (mut unicode_mode, mut unicode_sets_mode) = (false, false);
for ch in flags.chars() {
if ch == 'u' {
unicode_mode = true;
}
if ch == 'v' {
unicode_mode = true;
unicode_sets_mode = true;
}
}
ParserOptions { unicode_mode, unicode_sets_mode, ..self }
}
}