swc_ecma_transforms_optimization/
const_modules.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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
};

use dashmap::DashMap;
use once_cell::sync::Lazy;
use rustc_hash::FxHashMap;
use swc_atoms::{atom, JsWord};
use swc_common::{
    collections::ARandomState,
    errors::HANDLER,
    sync::Lrc,
    util::{move_map::MoveMap, take::Take},
    FileName, SourceMap,
};
use swc_ecma_ast::*;
use swc_ecma_parser::parse_file_as_expr;
use swc_ecma_utils::drop_span;
use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith};

pub fn const_modules(
    cm: Lrc<SourceMap>,
    globals: FxHashMap<JsWord, FxHashMap<JsWord, String>>,
) -> impl Pass {
    visit_mut_pass(ConstModules {
        globals: globals
            .into_iter()
            .map(|(src, map)| {
                let map = map
                    .into_iter()
                    .map(|(key, value)| {
                        let value = parse_option(&cm, &key, value);

                        (key, value)
                    })
                    .collect();

                (src, map)
            })
            .collect(),
        scope: Default::default(),
    })
}

fn parse_option(cm: &SourceMap, name: &str, src: String) -> Arc<Expr> {
    static CACHE: Lazy<DashMap<String, Arc<Expr>, ARandomState>> = Lazy::new(DashMap::default);

    let fm = cm.new_source_file(
        FileName::Internal(format!("<const-module-{}.js>", name)).into(),
        src,
    );
    if let Some(expr) = CACHE.get(&**fm.src) {
        return expr.clone();
    }

    let expr = parse_file_as_expr(
        &fm,
        Default::default(),
        Default::default(),
        None,
        &mut Vec::new(),
    )
    .map_err(|e| {
        if HANDLER.is_set() {
            HANDLER.with(|h| e.into_diagnostic(h).emit())
        }
    })
    .map(drop_span)
    .unwrap_or_else(|()| {
        panic!(
            "failed to parse jsx option {}: '{}' is not an expression",
            name, fm.src,
        )
    });

    let expr = Arc::new(*expr);

    CACHE.insert((*fm.src).clone(), expr.clone());

    expr
}

struct ConstModules {
    globals: HashMap<JsWord, HashMap<JsWord, Arc<Expr>>>,
    scope: Scope,
}

#[derive(Default)]
struct Scope {
    namespace: HashSet<Id>,
    imported: HashMap<JsWord, Arc<Expr>>,
}

impl VisitMut for ConstModules {
    noop_visit_mut_type!(fail);

    fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) {
        *n = n.take().move_flat_map(|item| match item {
            ModuleItem::ModuleDecl(ModuleDecl::Import(import)) => {
                let entry = self.globals.get(&import.src.value);
                if let Some(entry) = entry {
                    for s in &import.specifiers {
                        match *s {
                            ImportSpecifier::Named(ref s) => {
                                let imported = s
                                    .imported
                                    .as_ref()
                                    .map(|m| match m {
                                        ModuleExportName::Ident(id) => &id.sym,
                                        ModuleExportName::Str(s) => &s.value,
                                    })
                                    .unwrap_or(&s.local.sym);
                                let value = entry.get(imported).cloned().unwrap_or_else(|| {
                                    panic!(
                                        "The requested const_module `{}` does not provide an \
                                         export named `{}`",
                                        import.src.value, imported
                                    )
                                });
                                self.scope.imported.insert(imported.clone(), value);
                            }
                            ImportSpecifier::Namespace(ref s) => {
                                self.scope.namespace.insert(s.local.to_id());
                            }
                            ImportSpecifier::Default(ref s) => {
                                let imported = &s.local.sym;
                                let default_import_key = atom!("default");
                                let value =
                                    entry.get(&default_import_key).cloned().unwrap_or_else(|| {
                                        panic!(
                                            "The requested const_module `{}` does not provide \
                                             default export",
                                            import.src.value
                                        )
                                    });
                                self.scope.imported.insert(imported.clone(), value);
                            }
                        };
                    }

                    None
                } else {
                    Some(import.into())
                }
            }
            _ => Some(item),
        });

        if self.scope.imported.is_empty() && self.scope.namespace.is_empty() {
            return;
        }

        n.visit_mut_children_with(self);
    }

    fn visit_mut_expr(&mut self, n: &mut Expr) {
        match n {
            Expr::Ident(ref id @ Ident { ref sym, .. }) => {
                if let Some(value) = self.scope.imported.get(sym) {
                    *n = (**value).clone();
                    return;
                }

                if self.scope.namespace.contains(&id.to_id()) {
                    panic!(
                        "The const_module namespace `{}` cannot be used without member accessor",
                        sym
                    )
                }
            }
            Expr::Member(MemberExpr { obj, prop, .. }) if obj.is_ident() => {
                if let Some(module_name) = obj
                    .as_ident()
                    .filter(|member_obj| self.scope.namespace.contains(&member_obj.to_id()))
                    .map(|member_obj| &member_obj.sym)
                {
                    let imported_name = match prop {
                        MemberProp::Ident(ref id) => &id.sym,
                        MemberProp::Computed(ref p) => match &*p.expr {
                            Expr::Lit(Lit::Str(s)) => &s.value,
                            _ => return,
                        },
                        MemberProp::PrivateName(..) => return,
                    };

                    let value = self
                        .globals
                        .get(module_name)
                        .and_then(|entry| entry.get(imported_name))
                        .unwrap_or_else(|| {
                            panic!(
                                "The requested const_module `{}` does not provide an export named \
                                 `{}`",
                                module_name, imported_name
                            )
                        });

                    *n = (**value).clone();
                } else {
                    n.visit_mut_children_with(self);
                }
            }
            _ => {
                n.visit_mut_children_with(self);
            }
        };
    }

    fn visit_mut_prop(&mut self, n: &mut Prop) {
        match n {
            Prop::Shorthand(id) => {
                if let Some(value) = self.scope.imported.get(&id.sym) {
                    *n = Prop::KeyValue(KeyValueProp {
                        key: id.take().into(),
                        value: Box::new((**value).clone()),
                    });
                    return;
                }

                if self.scope.namespace.contains(&id.to_id()) {
                    panic!(
                        "The const_module namespace `{}` cannot be used without member accessor",
                        id.sym
                    )
                }
            }
            _ => n.visit_mut_children_with(self),
        }
    }
}