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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
use pmutil::q;
use proc_macro2::TokenStream;
use swc_macros_common::call_site;
use syn::{FnArg, Ident, ImplItem, ImplItemMethod, ItemImpl, Pat, Path, Stmt};

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::Method(m) => ImplItem::Method(expander.patch_method(m)),
                _ => item,
            })
            .collect(),
        ..item
    }
}

fn detect_mode(i: &ItemImpl) -> Mode {
    if i.items.iter().any(|item| match item {
        ImplItem::Method(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", q!({ swc_ecma_ast::Stmt })),
            ("stmts", q!({ Vec<swc_ecma_ast::Stmt> })),
            ("module_decl", q!({ swc_ecma_ast::ModuleDecl })),
            ("module_item", q!({ swc_ecma_ast::ModuleItem })),
            ("module_items", q!({ Vec<swc_ecma_ast::ModuleItem> })),
            ("expr", q!({ swc_ecma_ast::Expr })),
            ("exprs", q!({ Vec<Box<swc_ecma_ast::Expr>> })),
            ("decl", q!({ swc_ecma_ast::Decl })),
            ("pat", q!({ swc_ecma_ast::Pat })),
        ];

        for (name, ty) in list {
            let has = items.iter().any(|item| match item {
                ImplItem::Method(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 => q!(
                    Vars {
                        method: &name,
                        Type: ty,
                    },
                    {
                        fn method(&mut self, node: Type) -> Type {
                            node.fold_children_with(self)
                        }
                    }
                ),
                Mode::VisitMut => q!(
                    Vars {
                        method: &name,
                        Type: ty,
                    },
                    {
                        fn method(&mut self, node: &mut Type) {
                            node.visit_mut_children_with(self)
                        }
                    }
                ),
            };

            items.push(method.parse());
        }

        items
    }

    /// Add fast path to a method
    fn patch_method(&self, mut m: ImplItemMethod) -> ImplItemMethod {
        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 fast_path = match self.mode {
            Mode::Fold => q!(
                Vars {
                    Checker: &self.handler,
                    arg
                },
                {
                    if !swc_ecma_transforms_base::perf::should_work::<Checker, _>(&arg) {
                        return arg;
                    }
                }
            )
            .parse::<Stmt>(),
            Mode::VisitMut => q!(
                Vars {
                    Checker: &self.handler,
                    arg
                },
                {
                    if !swc_ecma_transforms_base::perf::should_work::<Checker, _>(&*arg) {
                        return;
                    }
                }
            )
            .parse::<Stmt>(),
        };
        let mut stmts = vec![fast_path];
        stmts.extend(m.block.stmts);

        m.block.stmts = stmts;
        m
    }
}