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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use crate::{
    pass::Pass,
    util::{
        drop_span,
        options::{CM, SESSION},
        ExprFactory, HANDLER,
    },
};
use ast::*;
use chashmap::CHashMap;
use serde::{Deserialize, Serialize};
use std::{iter, mem, sync::Arc};
use swc_atoms::JsWord;
use swc_common::{FileName, Fold, FoldWith, Spanned, DUMMY_SP};
use swc_ecma_parser::{Parser, SourceFileInput, Syntax};

#[cfg(test)]
mod tests;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Options {
    #[serde(default = "default_pragma")]
    pub pragma: String,
    #[serde(default = "default_pragma_frag")]
    pub pragma_frag: String,

    #[serde(default = "default_throw_if_namespace")]
    pub throw_if_namespace: bool,

    #[serde(default)]
    pub development: bool,

    #[serde(default)]
    pub use_builtins: bool,
}

impl Default for Options {
    fn default() -> Self {
        Options {
            pragma: default_pragma(),
            pragma_frag: default_pragma_frag(),
            throw_if_namespace: default_throw_if_namespace(),
            development: false,
            use_builtins: false,
        }
    }
}

fn default_pragma() -> String {
    "React.createElement".into()
}

fn default_pragma_frag() -> String {
    "React.Fragment".into()
}

fn default_throw_if_namespace() -> bool {
    true
}

fn parse_option(name: &str, src: String) -> Box<Expr> {
    lazy_static! {
        static ref CACHE: CHashMap<Arc<String>, Box<Expr>> = CHashMap::with_capacity(2);
    }

    let fm = CM.new_source_file(FileName::Custom(format!("<jsx-config-{}.js>", name)), src);
    if let Some(expr) = CACHE.get(&fm.src) {
        return expr.clone();
    }

    let expr = Parser::new(
        *SESSION,
        Syntax::default(),
        SourceFileInput::from(&*fm),
        None,
    )
    .parse_expr()
    .map_err(|mut e| {
        e.emit();
    })
    .map(drop_span)
    .unwrap_or_else(|()| {
        panic!(
            "faield to parse jsx option {}: '{}' is not an expression",
            name, fm.src,
        )
    });

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

    expr
}

/// `@babel/plugin-transform-react-jsx`
///
/// Turn JSX into React function calls
pub fn jsx(options: Options) -> impl Pass {
    Jsx {
        pragma: ExprOrSuper::Expr(parse_option("pragma", options.pragma)),
        pragma_frag: ExprOrSpread {
            spread: None,
            expr: parse_option("pragmaFrag", options.pragma_frag),
        },
        use_builtins: options.use_builtins,
        throw_if_namespace: options.throw_if_namespace,
    }
}

struct Jsx {
    pragma: ExprOrSuper,
    pragma_frag: ExprOrSpread,
    use_builtins: bool,
    throw_if_namespace: bool,
}

impl Jsx {
    fn jsx_frag_to_expr(&mut self, el: JSXFragment) -> Expr {
        let span = el.span();

        Expr::Call(CallExpr {
            span,
            callee: self.pragma.clone(),
            args: iter::once(self.pragma_frag.clone())
                // attribute: null
                .chain(iter::once(Lit::Null(Null { span: DUMMY_SP }).as_arg()))
                .chain({
                    // Children
                    el.children
                        .into_iter()
                        .filter_map(|c| self.jsx_elem_child_to_expr(c))
                })
                .collect(),
            type_args: None,
        })
    }

    fn jsx_elem_to_expr(&mut self, el: JSXElement) -> Expr {
        let span = el.span();

        let name = self.jsx_name(el.opening.name);

        Expr::Call(CallExpr {
            span,
            callee: self.pragma.clone(),
            args: iter::once(name.as_arg())
                .chain(iter::once({
                    // Attributes
                    self.fold_attrs(el.opening.attrs).as_arg()
                }))
                .chain({
                    // Children
                    el.children
                        .into_iter()
                        .filter_map(|c| self.jsx_elem_child_to_expr(c))
                })
                .collect(),
            type_args: Default::default(),
        })
    }

    fn jsx_elem_child_to_expr(&mut self, c: JSXElementChild) -> Option<ExprOrSpread> {
        Some(match c {
            JSXElementChild::JSXText(text) => {
                // TODO(kdy1): Optimize
                let s = Str {
                    span: text.span,
                    has_escape: text.raw != text.value,
                    value: jsx_text_to_str(text.value),
                };
                if s.value.is_empty() {
                    return None;
                }
                Lit::Str(s).as_arg()
            }
            JSXElementChild::JSXExprContainer(JSXExprContainer {
                expr: JSXExpr::Expr(e),
            }) => e.as_arg(),
            JSXElementChild::JSXExprContainer(JSXExprContainer {
                expr: JSXExpr::JSXEmptyExpr(..),
            }) => return None,
            JSXElementChild::JSXElement(el) => self.jsx_elem_to_expr(*el).as_arg(),
            JSXElementChild::JSXFragment(el) => self.jsx_frag_to_expr(el).as_arg(),
            JSXElementChild::JSXSpreadChild(JSXSpreadChild { .. }) => {
                unimplemented!("jsx sperad child")
            }
        })
    }

    fn fold_attrs(&mut self, attrs: Vec<JSXAttrOrSpread>) -> Box<Expr> {
        if attrs.is_empty() {
            return box Expr::Lit(Lit::Null(Null { span: DUMMY_SP }));
        }

        let is_complex = attrs.iter().any(|a| match *a {
            JSXAttrOrSpread::SpreadElement(..) => true,
            _ => false,
        });

        if is_complex {
            let mut args = vec![];
            let mut cur_obj_props = vec![];
            macro_rules! check {
                () => {{
                    if args.is_empty() || !cur_obj_props.is_empty() {
                        args.push(
                            ObjectLit {
                                span: DUMMY_SP,
                                props: mem::replace(&mut cur_obj_props, vec![]),
                            }
                            .as_arg(),
                        )
                    }
                }};
            }
            for attr in attrs {
                match attr {
                    JSXAttrOrSpread::JSXAttr(a) => {
                        cur_obj_props.push(PropOrSpread::Prop(box attr_to_prop(a)))
                    }
                    JSXAttrOrSpread::SpreadElement(e) => {
                        check!();
                        args.push(e.expr.as_arg());
                    }
                }
            }
            check!();

            // calls `_extends` or `Object.assign`
            box Expr::Call(CallExpr {
                span: DUMMY_SP,
                callee: {
                    if self.use_builtins {
                        member_expr!(DUMMY_SP, Object.assign).as_callee()
                    } else {
                        helper!(extends, "extends")
                    }
                },
                args,
                type_args: None,
            })
        } else {
            box Expr::Object(ObjectLit {
                span: DUMMY_SP,
                props: attrs
                    .into_iter()
                    .map(|a| match a {
                        JSXAttrOrSpread::JSXAttr(a) => a,
                        _ => unreachable!(),
                    })
                    .map(attr_to_prop)
                    .map(Box::new)
                    .map(PropOrSpread::Prop)
                    .collect(),
            })
        }
    }
}

impl Fold<Expr> for Jsx {
    fn fold(&mut self, expr: Expr) -> Expr {
        let expr = expr.fold_children(self);

        match expr {
            Expr::Paren(ParenExpr {
                expr: box Expr::JSXElement(el),
                ..
            })
            | Expr::JSXElement(el) => {
                // <div></div> => React.createElement('div', null);
                self.jsx_elem_to_expr(*el)
            }
            Expr::Paren(ParenExpr {
                expr: box Expr::JSXFragment(frag),
                ..
            })
            | Expr::JSXFragment(frag) => {
                // <></> => React.createElement(React.Fragment, null);
                self.jsx_frag_to_expr(frag)
            }
            _ => expr,
        }
    }
}

impl Jsx {
    fn jsx_name(&self, name: JSXElementName) -> Box<Expr> {
        let span = name.span();
        match name {
            JSXElementName::Ident(i) => {
                // If it starts with lowercase digit
                let c = i.sym.chars().next().unwrap();

                if i.sym == js_word!("this") {
                    return box Expr::This(ThisExpr { span });
                }

                if c.is_ascii_lowercase() {
                    box Expr::Lit(Lit::Str(Str {
                        span,
                        value: i.sym,
                        has_escape: false,
                    }))
                } else {
                    box Expr::Ident(i)
                }
            }
            JSXElementName::JSXNamespacedName(JSXNamespacedName { ref ns, ref name }) => {
                if self.throw_if_namespace {
                    HANDLER.with(|handler| {
                        handler
                            .struct_span_err(
                                span,
                                "JSX Namespace is disabled by default because react does not \
                                 support it yet. You can specify \
                                 jsc.transform.react.throwIfNamespace to false to override \
                                 default behavior",
                            )
                            .emit()
                    });
                }
                box Expr::Lit(Lit::Str(Str {
                    span,
                    value: format!("{}:{}", ns.sym, name.sym).into(),
                    has_escape: false,
                }))
            }
            JSXElementName::JSXMemberExpr(JSXMemberExpr { obj, prop }) => {
                fn convert_obj(obj: JSXObject) -> ExprOrSuper {
                    let span = obj.span();

                    match obj {
                        JSXObject::Ident(i) => {
                            if i.sym == js_word!("this") {
                                return ExprOrSuper::Expr(box Expr::This(ThisExpr { span }));
                            }
                            i.as_obj()
                        }
                        JSXObject::JSXMemberExpr(box JSXMemberExpr { obj, prop }) => MemberExpr {
                            span,
                            obj: convert_obj(obj),
                            prop: box Expr::Ident(prop),
                            computed: false,
                        }
                        .as_obj(),
                    }
                }
                box Expr::Member(MemberExpr {
                    span,
                    obj: convert_obj(obj),
                    prop: box Expr::Ident(prop),
                    computed: false,
                })
            }
        }
    }
}

fn attr_to_prop(a: JSXAttr) -> Prop {
    let key = to_prop_name(a.name);
    let value = a.value.unwrap_or_else(|| {
        box Expr::Lit(Lit::Bool(Bool {
            span: key.span(),
            value: true,
        }))
    });
    Prop::KeyValue(KeyValueProp { key, value })
}

fn to_prop_name(n: JSXAttrName) -> PropName {
    let span = n.span();

    match n {
        JSXAttrName::Ident(i) => {
            if i.sym.contains('-') {
                PropName::Str(Str {
                    span,
                    value: i.sym,
                    has_escape: false,
                })
            } else {
                PropName::Ident(i)
            }
        }
        JSXAttrName::JSXNamespacedName(JSXNamespacedName { ns, name }) => PropName::Str(Str {
            span,
            value: format!("{}:{}", ns.sym, name.sym).into(),
            has_escape: false,
        }),
    }
}

fn jsx_text_to_str(t: JsWord) -> JsWord {
    if !t.contains(' ') && !t.contains('\n') {
        return t;
    }

    let mut buf = String::new();
    for s in t.replace("\n", " ").split_ascii_whitespace() {
        buf.push_str(s);
        buf.push(' ');
    }

    buf.into()
}