swc_ecma_compat_es2015/
sticky_regex.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use swc_ecma_ast::*;
use swc_ecma_transforms_base::perf::Parallel;
use swc_ecma_utils::{quote_ident, ExprFactory};
use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith};
use swc_trace_macro::swc_trace;

/// Compile ES2015 sticky regex to an ES5 RegExp constructor
///
///# Example
///## In
///
/// ```js
/// /o+/y;
/// ```
///
///## Out
///
/// ```js
/// new RegExp("o+", "y")
/// ```
pub fn sticky_regex() -> impl Pass {
    visit_mut_pass(StickyRegex)
}

struct StickyRegex;

impl Parallel for StickyRegex {
    fn merge(&mut self, _: Self) {}

    fn create(&self) -> Self {
        StickyRegex
    }
}

#[swc_trace]
impl VisitMut for StickyRegex {
    noop_visit_mut_type!(fail);

    fn visit_mut_expr(&mut self, e: &mut Expr) {
        e.visit_mut_children_with(self);

        if let Expr::Lit(Lit::Regex(Regex { exp, flags, span })) = e {
            if flags.contains('y') {
                *e = NewExpr {
                    span: *span,
                    callee: Box::new(quote_ident!(Default::default(), *span, "RegExp").into()),
                    args: Some(vec![exp.clone().as_arg(), flags.clone().as_arg()]),
                    ..Default::default()
                }
                .into()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use swc_ecma_transforms_testing::test;

    use super::*;

    test!(
        ::swc_ecma_parser::Syntax::default(),
        |_| sticky_regex(),
        babel_basic,
        "var re = /o\"'+/y;"
    );

    test!(
        ::swc_ecma_parser::Syntax::default(),
        |_| sticky_regex(),
        babel_ignore_non_sticky,
        "var re = /o+/;"
    );
}