swc_ecma_transforms_macros/
fast.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
use proc_macro2::TokenStream;
use quote::quote;
use swc_macros_common::call_site;
use syn::{parse_quote, FnArg, Ident, ImplItem, ImplItemFn, ItemImpl, Pat, Path};

use crate::common::Mode;

pub fn expand(attr: TokenStream, item: ItemImpl) -> ItemImpl {
    let expander = Expander {
        handler: syn::parse2(attr).expect("Usage should be like #[fast_path(ArrowVisitor)]"),
        mode: detect_mode(&item),
    };
    let items = expander.inject_default_methods(item.items);

    ItemImpl {
        items: items
            .into_iter()
            .map(|item| match item {
                ImplItem::Fn(m) => ImplItem::Fn(expander.patch_method(m)),
                _ => item,
            })
            .collect(),
        ..item
    }
}

fn detect_mode(i: &ItemImpl) -> Mode {
    if i.items.iter().any(|item| match item {
        ImplItem::Fn(m) => m.sig.ident.to_string().starts_with("fold"),
        _ => false,
    }) {
        return Mode::Fold;
    }

    Mode::VisitMut
}

struct Expander {
    mode: Mode,
    handler: Path,
}

impl Expander {
    fn inject_default_methods(&self, mut items: Vec<ImplItem>) -> Vec<ImplItem> {
        let list = &[
            ("stmt", quote!(swc_ecma_ast::Stmt)),
            ("stmts", quote!(Vec<swc_ecma_ast::Stmt>)),
            ("module_decl", quote!(swc_ecma_ast::ModuleDecl)),
            ("module_item", quote!(swc_ecma_ast::ModuleItem)),
            ("module_items", quote!(Vec<swc_ecma_ast::ModuleItem>)),
            ("expr", quote!(swc_ecma_ast::Expr)),
            ("exprs", quote!(Vec<Box<swc_ecma_ast::Expr>>)),
            ("decl", quote!(swc_ecma_ast::Decl)),
            ("pat", quote!(swc_ecma_ast::Pat)),
        ];

        for (name, ty) in list {
            let has = items.iter().any(|item| match item {
                ImplItem::Fn(i) => i.sig.ident.to_string().ends_with(name),
                _ => false,
            });
            if has {
                continue;
            }
            let name = Ident::new(&format!("{}_{}", self.mode.prefix(), name), call_site());

            let method = match self.mode {
                Mode::Fold => parse_quote!(
                    fn #name(&mut self, node: #ty) -> #ty {
                        node.fold_children_with(self)
                    }
                ),
                Mode::VisitMut => parse_quote!(
                    fn #name(&mut self, node: &mut #ty) {
                        node.visit_mut_children_with(self)
                    }
                ),
            };

            items.push(method);
        }

        items
    }

    /// Add fast path to a method
    fn patch_method(&self, mut m: ImplItemFn) -> ImplItemFn {
        let ty_arg = m
            .sig
            .inputs
            .last()
            .expect("method of Fold / VisitMut must accept two parameters");
        let ty_arg = match ty_arg {
            FnArg::Receiver(_) => unreachable!(),
            FnArg::Typed(ty) => ty,
        };
        if m.sig.ident == "visit_mut_ident" || m.sig.ident == "fold_ident" {
            return m;
        }
        if m.block.stmts.is_empty() {
            return m;
        }

        let arg = match &*ty_arg.pat {
            Pat::Ident(i) => &i.ident,
            _ => unimplemented!(
                "Fast-path injection for Fold / VisitMut where pattern is not an ident"
            ),
        };

        let checker = &self.handler;

        let fast_path = match self.mode {
            Mode::Fold => parse_quote!(
                if !swc_ecma_transforms_base::perf::should_work::<#checker, _>(&#arg) {
                    return #arg;
                }
            ),
            Mode::VisitMut => parse_quote!(
                if !swc_ecma_transforms_base::perf::should_work::<#checker, _>(&*#arg) {
                    return;
                }
            ),
        };
        let mut stmts = vec![fast_path];
        stmts.extend(m.block.stmts);

        m.block.stmts = stmts;
        m
    }
}