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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
|
extern crate swc_common;
extern crate swc_ecma_ast;
use crate::test_utils::to_swc::Program;
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use unicode_id::UnicodeID;
/// Configuration.
#[derive(Debug, Default, Clone)]
pub struct Options {
/// Place to import a provider from.
///
/// See [MDX provider](https://mdxjs.com/docs/using-mdx/#mdx-provider)
/// on the MDX website for more info.
pub provider_import_source: Option<String>,
/// Whether to add extra information to error messages in generated code.
/// This is not yet supported.
pub development: bool,
}
/// Rewrite JSX in an MDX file so that components can be passed in and provided.
#[allow(dead_code)]
pub fn jsx_rewrite(mut program: Program, options: &Options) -> Program {
let mut state = State {
scopes: vec![],
provider: options.provider_import_source.is_some(),
create_provider_import: false,
create_error_helper: false,
};
state.enter(Some(Info::default()));
program.module.visit_mut_with(&mut state);
// If a provider is used (and can be used), import it.
if let Some(source) = &options.provider_import_source {
if state.create_provider_import {
program
.module
.body
.insert(0, create_import_provider(source))
}
}
// If potentially missing components are used, add the helper used for
// errors.
if state.create_error_helper {
program.module.body.push(create_error_helper());
}
program
}
/// Collection of different SWC functions.
#[derive(Debug)]
enum Func<'a> {
/// Function declaration.
Decl(&'a mut swc_ecma_ast::FnDecl),
/// Function expression.
Expr(&'a mut swc_ecma_ast::FnExpr),
/// Arrow function.
Arrow(&'a mut swc_ecma_ast::ArrowExpr),
}
/// Info for a function scope.
#[derive(Debug, Default, Clone)]
struct Info {
/// Function name.
name: Option<String>,
/// Used objects (`a` in `<a.b />`).
objects: Vec<String>,
/// Used components (`<A />`).
components: Vec<String>,
/// Used literals (`<a />`).
tags: Vec<String>,
/// List of JSX identifiers of literal tags that are not valid JS
/// identifiers in the shape of `Vec<(invalid, valid)>`.
///
/// Example:
///
/// ```
/// vec![("a-b".into(), "_component0".into())]
/// ```
aliases: Vec<(String, String)>,
/// Non-literal references in the shape of `Vec<(name, is_component)>`.
///
/// Example:
///
/// ```
/// vec![("a".into(), false), ("a.b".into(), true)]
/// ```
// To do: add positional info later.
references: Vec<(String, bool)>,
}
/// Scope (block or function/global).
#[derive(Debug, Clone)]
struct Scope {
/// If this is a function (or global) scope, we track info.
info: Option<Info>,
/// Things that are defined in this scope.
defined: Vec<String>,
}
/// Context.
#[derive(Debug, Default, Clone)]
struct State {
/// List of current scopes.
scopes: Vec<Scope>,
/// Whether the user uses a provider.
provider: bool,
/// Whether a provider is referenced.
create_provider_import: bool,
/// Whether a missing component helper is referenced.
///
/// When things are referenced that might not be defined, we reference a
/// helper function to throw when they are missing.
create_error_helper: bool,
}
impl State {
/// Open a new scope.
fn enter(&mut self, info: Option<Info>) {
self.scopes.push(Scope {
info,
defined: vec![],
});
}
/// Close the current scope.
fn exit(&mut self) -> Scope {
self.scopes.pop().expect("expected scope")
}
/// Close a function.
fn exit_func(&mut self, func: Func) {
let mut scope = self.exit();
let mut defaults = vec![];
let mut info = scope.info.take().unwrap();
let mut index = 0;
// Create defaults for tags.
//
// ```jsx
// {h1: 'h1'}
// ```
while index < info.tags.len() {
let name = &info.tags[index];
defaults.push(swc_ecma_ast::PropOrSpread::Prop(Box::new(
swc_ecma_ast::Prop::KeyValue(swc_ecma_ast::KeyValueProp {
key: if is_identifier_name(name) {
swc_ecma_ast::PropName::Ident(create_ident(name))
} else {
swc_ecma_ast::PropName::Str(swc_ecma_ast::Str {
value: name.clone().into(),
span: swc_common::DUMMY_SP,
raw: None,
})
},
value: Box::new(swc_ecma_ast::Expr::Lit(swc_ecma_ast::Lit::Str(
swc_ecma_ast::Str {
value: name.clone().into(),
span: swc_common::DUMMY_SP,
raw: None,
},
))),
}),
)));
index += 1;
}
let mut actual = info.components.split_off(0);
let mut index = 0;
// In some cases, a component is used directly (`<X>`) but it’s also
// used as an object (`<X.Y>`).
while index < info.objects.len() {
if !actual.contains(&info.objects[index]) {
actual.push(info.objects[index].clone());
}
index += 1;
}
let mut statements = vec![];
if !defaults.is_empty() || !actual.is_empty() || !info.aliases.is_empty() {
let mut parameters = vec![];
// Use a provider, if configured.
//
// ```jsx
// _provideComponents()
// ```
if self.provider {
self.create_provider_import = true;
parameters.push(swc_ecma_ast::Expr::Call(swc_ecma_ast::CallExpr {
callee: swc_ecma_ast::Callee::Expr(Box::new(create_ident_expression(
"_provideComponents",
))),
args: vec![],
type_args: None,
span: swc_common::DUMMY_SP,
}));
}
// Accept `components` as a prop if this is the `MDXContent` or
// `_createMdxContent` function.
//
// ```jsx
// props.components
// ```
if is_props_receiving_fn(&info.name) {
parameters.push(swc_ecma_ast::Expr::Member(swc_ecma_ast::MemberExpr {
obj: Box::new(create_ident_expression("props")),
prop: swc_ecma_ast::MemberProp::Ident(create_ident("components")),
span: swc_common::DUMMY_SP,
}));
}
// Inject an object at the start, when:
// - there are defaults,
// - there are two sources
//
// ```jsx
// (_provideComponents(), props.components)
// ()
// ```
//
// To:
//
// ```jsx
// ({}, _provideComponents(), props.components)
// ({h1: 'h1'})
// ```
if !defaults.is_empty() || parameters.len() > 1 {
parameters.insert(
0,
swc_ecma_ast::Expr::Object(swc_ecma_ast::ObjectLit {
props: defaults,
span: swc_common::DUMMY_SP,
}),
);
}
// Merge things and prevent errors.
//
// ```jsx
// {}, _provideComponents(), props.components
// props.components
// _provideComponents()
// ```
//
// To:
//
// ```jsx
// Object.assign({}, _provideComponents(), props.components)
// props.components || {}
// _provideComponents()
// ```
let mut components_init = if parameters.len() > 1 {
let mut args = vec![];
parameters.reverse();
while let Some(param) = parameters.pop() {
args.push(swc_ecma_ast::ExprOrSpread {
spread: None,
expr: Box::new(param),
});
}
swc_ecma_ast::Expr::Call(swc_ecma_ast::CallExpr {
callee: swc_ecma_ast::Callee::Expr(Box::new(swc_ecma_ast::Expr::Member(
swc_ecma_ast::MemberExpr {
obj: Box::new(create_ident_expression("Object")),
prop: swc_ecma_ast::MemberProp::Ident(create_ident("assign")),
span: swc_common::DUMMY_SP,
},
))),
args,
type_args: None,
span: swc_common::DUMMY_SP,
})
} else {
// Always one.
let param = parameters.pop().unwrap();
if let swc_ecma_ast::Expr::Member(_) = param {
create_binary_expression(
vec![
param,
swc_ecma_ast::Expr::Object(swc_ecma_ast::ObjectLit {
props: vec![],
span: swc_common::DUMMY_SP,
}),
],
swc_ecma_ast::BinaryOp::LogicalOr,
)
} else {
param
}
};
// Add components to scope.
//
// For `['MyComponent', 'MDXLayout']` this generates:
//
// ```js
// const {MyComponent, wrapper: MDXLayout} = _components
// ```
//
// Note that MDXLayout is special as it’s taken from
// `_components.wrapper`.
let components_pattern = if actual.is_empty() {
None
} else {
let mut props = vec![];
actual.reverse();
while let Some(key) = actual.pop() {
// `wrapper: MDXLayout`
if key == "MDXLayout" {
props.push(swc_ecma_ast::ObjectPatProp::KeyValue(
swc_ecma_ast::KeyValuePatProp {
key: swc_ecma_ast::PropName::Ident(create_ident("wrapper")),
value: Box::new(swc_ecma_ast::Pat::Ident(
swc_ecma_ast::BindingIdent {
id: create_ident(&key),
type_ann: None,
},
)),
},
))
}
// `MyComponent`
else {
props.push(swc_ecma_ast::ObjectPatProp::Assign(
swc_ecma_ast::AssignPatProp {
key: create_ident(&key),
value: None,
span: swc_common::DUMMY_SP,
},
))
}
}
Some(swc_ecma_ast::ObjectPat {
props,
optional: false,
span: swc_common::DUMMY_SP,
type_ann: None,
})
};
let mut declarators = vec![];
// If there are tags, they take them from `_components`, so we need
// to make it defined.
if !info.tags.is_empty() {
declarators.push(swc_ecma_ast::VarDeclarator {
span: swc_common::DUMMY_SP,
name: swc_ecma_ast::Pat::Ident(swc_ecma_ast::BindingIdent {
id: create_ident("_components"),
type_ann: None,
}),
init: Some(Box::new(components_init)),
definite: false,
});
components_init = create_ident_expression("_components");
}
// For JSX IDs that can’t be represented as JavaScript IDs (as in,
// those with dashes, such as `custom-element`), we generated a
// separate variable that is a valid JS ID (such as `_component0`),
// and here we take it from components:
// ```js
// const _component0 = _components['custom-element']
// ```
if !info.aliases.is_empty() {
info.aliases.reverse();
while let Some((id, name)) = info.aliases.pop() {
declarators.push(swc_ecma_ast::VarDeclarator {
span: swc_common::DUMMY_SP,
name: swc_ecma_ast::Pat::Ident(swc_ecma_ast::BindingIdent {
id: create_ident(&name),
type_ann: None,
}),
init: Some(Box::new(swc_ecma_ast::Expr::Member(
swc_ecma_ast::MemberExpr {
obj: Box::new(create_ident_expression("_components")),
prop: swc_ecma_ast::MemberProp::Computed(
swc_ecma_ast::ComputedPropName {
expr: Box::new(swc_ecma_ast::Expr::Lit(
swc_ecma_ast::Lit::Str(swc_ecma_ast::Str {
value: id.into(),
span: swc_common::DUMMY_SP,
raw: None,
}),
)),
span: swc_common::DUMMY_SP,
},
),
span: swc_common::DUMMY_SP,
},
))),
definite: false,
});
}
}
if let Some(pat) = components_pattern {
declarators.push(swc_ecma_ast::VarDeclarator {
name: swc_ecma_ast::Pat::Object(pat),
init: Some(Box::new(components_init)),
span: swc_common::DUMMY_SP,
definite: false,
});
}
// Add the variable declaration.
statements.push(swc_ecma_ast::Stmt::Decl(swc_ecma_ast::Decl::Var(Box::new(
swc_ecma_ast::VarDecl {
kind: swc_ecma_ast::VarDeclKind::Const,
decls: declarators,
span: swc_common::DUMMY_SP,
declare: false,
},
))));
}
// Add checks at runtime to verify that object/components are passed.
//
// ```js
// if (!a) _missingMdxReference("a", false);
// if (!a.b) _missingMdxReference("a.b", true);
// ```
for (id, component) in info.references {
self.create_error_helper = true;
statements.push(swc_ecma_ast::Stmt::If(swc_ecma_ast::IfStmt {
test: Box::new(swc_ecma_ast::Expr::Unary(swc_ecma_ast::UnaryExpr {
op: swc_ecma_ast::UnaryOp::Bang,
arg: Box::new(create_member_expression(&id)),
span: swc_common::DUMMY_SP,
})),
cons: Box::new(swc_ecma_ast::Stmt::Expr(swc_ecma_ast::ExprStmt {
span: swc_common::DUMMY_SP,
expr: Box::new(swc_ecma_ast::Expr::Call(swc_ecma_ast::CallExpr {
callee: swc_ecma_ast::Callee::Expr(Box::new(create_ident_expression(
"_missingMdxReference",
))),
args: vec![
swc_ecma_ast::ExprOrSpread {
spread: None,
expr: Box::new(swc_ecma_ast::Expr::Lit(swc_ecma_ast::Lit::Str(
swc_ecma_ast::Str {
value: id.into(),
span: swc_common::DUMMY_SP,
raw: None,
},
))),
},
swc_ecma_ast::ExprOrSpread {
spread: None,
expr: Box::new(swc_ecma_ast::Expr::Lit(swc_ecma_ast::Lit::Bool(
swc_ecma_ast::Bool {
value: component,
span: swc_common::DUMMY_SP,
},
))),
},
],
type_args: None,
span: swc_common::DUMMY_SP,
})),
})),
alt: None,
span: swc_common::DUMMY_SP,
}));
}
// Add statements to functions.
if !statements.is_empty() {
let mut body: &mut swc_ecma_ast::BlockStmt = match func {
Func::Expr(expr) => {
if expr.function.body.is_none() {
expr.function.body = Some(swc_ecma_ast::BlockStmt {
stmts: vec![],
span: swc_common::DUMMY_SP,
});
}
expr.function.body.as_mut().unwrap()
}
Func::Decl(decl) => {
if decl.function.body.is_none() {
decl.function.body = Some(swc_ecma_ast::BlockStmt {
stmts: vec![],
span: swc_common::DUMMY_SP,
});
}
decl.function.body.as_mut().unwrap()
}
Func::Arrow(arr) => {
if let swc_ecma_ast::BlockStmtOrExpr::Expr(expr) = &mut arr.body {
arr.body =
swc_ecma_ast::BlockStmtOrExpr::BlockStmt(swc_ecma_ast::BlockStmt {
stmts: vec![swc_ecma_ast::Stmt::Return(swc_ecma_ast::ReturnStmt {
// To do: figure out non-clone.
arg: Some(expr.clone()),
span: swc_common::DUMMY_SP,
})],
span: swc_common::DUMMY_SP,
});
}
arr.body.as_mut_block_stmt().unwrap()
}
};
statements.append(&mut body.stmts.split_off(0));
body.stmts = statements;
}
}
/// Get the current function scope.
fn current_fn_scope_mut(&mut self) -> &mut Scope {
let mut index = self.scopes.len();
while index > 0 {
index -= 1;
if self.scopes[index].info.is_some() {
return &mut self.scopes[index];
}
}
unreachable!("expected scope")
}
/// Get the current scope.
fn current_scope_mut(&mut self) -> &mut Scope {
self.scopes.last_mut().expect("expected scope")
}
/// Get the top-level scope’s info.
fn current_top_level_info(&self) -> Option<&Info> {
if let Some(scope) = self.scopes.get(1) {
scope.info.as_ref()
} else {
None
}
}
/// Get the top-level scope’s info, mutably.
fn current_top_level_info_mut(&mut self) -> Option<&mut Info> {
if let Some(scope) = self.scopes.get_mut(1) {
scope.info.as_mut()
} else {
None
}
}
/// Check if `id` is in scope.
fn in_scope(&self, id: &String) -> bool {
let mut index = self.scopes.len();
while index > 0 {
index -= 1;
if self.scopes[index].defined.contains(id) {
return true;
}
}
false
}
/// Add an identifier to a scope.
fn add_id(&mut self, id: String, block: bool) {
let scope = if block {
self.current_scope_mut()
} else {
self.current_fn_scope_mut()
};
scope.defined.push(id);
}
// Add a pattern to a scope.
fn add_pat(&mut self, pat: &swc_ecma_ast::Pat, block: bool) {
match pat {
// `x`
swc_ecma_ast::Pat::Ident(d) => self.add_id(d.id.sym.to_string(), block),
// `...x`
swc_ecma_ast::Pat::Array(d) => {
let mut index = 0;
while index < d.elems.len() {
if let Some(d) = &d.elems[index] {
self.add_pat(d, block);
}
index += 1;
}
}
// `...x`
swc_ecma_ast::Pat::Rest(d) => self.add_pat(&d.arg, block),
// `{x=y}`
swc_ecma_ast::Pat::Assign(d) => self.add_pat(&d.left, block),
swc_ecma_ast::Pat::Object(d) => {
let mut index = 0;
while index < d.props.len() {
match &d.props[index] {
// `{...x}`
swc_ecma_ast::ObjectPatProp::Rest(d) => {
self.add_pat(&d.arg, block);
}
// `{key: value}`
swc_ecma_ast::ObjectPatProp::KeyValue(d) => {
self.add_pat(&d.value, block);
}
// `{key}` or `{key = value}`
swc_ecma_ast::ObjectPatProp::Assign(d) => {
self.add_id(d.key.to_string(), block);
}
}
index += 1;
}
}
// Ignore `Invalid` / `Expr`.
_ => {}
}
}
}
impl VisitMut for State {
noop_visit_mut_type!();
/// Rewrite JSX identifiers.
fn visit_mut_jsx_element(&mut self, node: &mut swc_ecma_ast::JSXElement) {
// If there is a top-level, non-global, scope which is a function.
if let Some(info) = self.current_top_level_info() {
// Rewrite only if we can rewrite.
if is_props_receiving_fn(&info.name) || self.provider {
match &node.opening.name {
// `<x.y>`, `<Foo.Bar>`, `<x.y.z>`.
swc_ecma_ast::JSXElementName::JSXMemberExpr(d) => {
let mut ids = vec![];
let mut mem = d;
loop {
ids.push(mem.prop.sym.to_string());
match &mem.obj {
swc_ecma_ast::JSXObject::Ident(d) => {
ids.push(d.sym.to_string());
break;
}
swc_ecma_ast::JSXObject::JSXMemberExpr(d) => {
mem = d;
}
}
}
ids.reverse();
let primary_id = ids.first().unwrap().clone();
let in_scope = self.in_scope(&primary_id);
if !in_scope {
let info_mut = self.current_top_level_info_mut().unwrap();
// To do: add positional info.
let mut index = 1;
while index <= ids.len() {
let full_id = ids[0..index].join(".");
let component = index == ids.len();
if let Some(reference) =
info_mut.references.iter_mut().find(|d| d.0 == full_id)
{
if component {
reference.1 = true;
}
} else {
info_mut.references.push((full_id, component))
}
index += 1;
}
if !info_mut.objects.contains(&primary_id) {
info_mut.objects.push(primary_id);
}
}
}
// `<foo>`, `<Foo>`, `<$>`, `<_bar>`, `<a_b>`.
swc_ecma_ast::JSXElementName::Ident(d) => {
// If the name is a valid ES identifier, and it doesn’t
// start with a lowercase letter, it’s a component.
// For example, `$foo`, `_bar`, `Baz` are all component
// names.
// But `foo` and `b-ar` are tag names.
let id = d.sym.to_string();
if is_literal_name(&id) {
// To do: ignore explicit JSX?
let mut invalid = None;
let name = if is_identifier_name(&id) {
swc_ecma_ast::JSXElementName::JSXMemberExpr(
swc_ecma_ast::JSXMemberExpr {
obj: swc_ecma_ast::JSXObject::Ident(create_ident(
"_components",
)),
prop: create_ident(&id),
},
)
} else {
let name = if let Some(invalid_ref) =
info.aliases.iter().find(|d| d.0 == id)
{
invalid_ref.1.clone()
} else {
let name = format!("_component{}", info.aliases.len());
invalid = Some((id.clone(), name.clone()));
name
};
swc_ecma_ast::JSXElementName::Ident(create_ident(&name))
};
let info_mut = self.current_top_level_info_mut().unwrap();
if !info_mut.tags.contains(&id) {
info_mut.tags.push(id);
}
if let Some(invalid) = invalid {
info_mut.aliases.push(invalid)
}
if let Some(closing) = node.closing.as_mut() {
closing.name = name.clone();
}
node.opening.name = name;
} else {
let mut is_layout = false;
// The MDXLayout is wrapped in a
if let Some(name) = &info.name {
if name == "MDXContent" && id == "MDXLayout" {
is_layout = true;
}
}
if !self.in_scope(&id) {
let info_mut = self.current_top_level_info_mut().unwrap();
if !is_layout {
if let Some(reference) =
info_mut.references.iter_mut().find(|d| d.0 == id)
{
reference.1 = true;
} else {
info_mut.references.push((id.clone(), true))
}
}
if !info_mut.components.contains(&id) {
info_mut.components.push(id);
}
}
}
}
// `<xml:thing>`.
swc_ecma_ast::JSXElementName::JSXNamespacedName(_) => {
// Ignore.
}
}
}
}
node.visit_mut_children_with(self);
}
/// Add specifiers of import declarations.
fn visit_mut_import_decl(&mut self, node: &mut swc_ecma_ast::ImportDecl) {
let mut index = 0;
while index < node.specifiers.len() {
let ident = match &node.specifiers[index] {
swc_ecma_ast::ImportSpecifier::Default(x) => &x.local.sym,
swc_ecma_ast::ImportSpecifier::Namespace(x) => &x.local.sym,
swc_ecma_ast::ImportSpecifier::Named(x) => &x.local.sym,
};
self.add_id(ident.to_string(), false);
index += 1;
}
node.visit_mut_children_with(self);
}
/// Add patterns of variable declarations.
fn visit_mut_var_decl(&mut self, node: &mut swc_ecma_ast::VarDecl) {
let block = node.kind != swc_ecma_ast::VarDeclKind::Var;
let mut index = 0;
while index < node.decls.len() {
self.add_pat(&node.decls[index].name, block);
index += 1;
}
node.visit_mut_children_with(self);
}
/// Add identifier of class declaration.
fn visit_mut_class_decl(&mut self, node: &mut swc_ecma_ast::ClassDecl) {
self.add_id(node.ident.sym.to_string(), false);
node.visit_mut_children_with(self);
}
/// On function declarations, add name, create scope, add parameters.
fn visit_mut_fn_decl(&mut self, node: &mut swc_ecma_ast::FnDecl) {
let id = node.ident.sym.to_string();
self.add_id(id.clone(), false);
self.enter(Some(Info {
name: Some(id),
..Default::default()
}));
let mut index = 0;
while index < node.function.params.len() {
self.add_pat(&node.function.params[index].pat, false);
index += 1;
}
node.visit_mut_children_with(self);
// Rewrite.
self.exit_func(Func::Decl(node));
}
/// On function expressions, add name, create scope, add parameters.
fn visit_mut_fn_expr(&mut self, node: &mut swc_ecma_ast::FnExpr) {
// Note: `periscopic` adds the ID to the newly generated scope, for
// fn expressions.
// That seems wrong?
let name = if let Some(ident) = &node.ident {
let id = ident.sym.to_string();
self.add_id(id.clone(), false);
Some(id)
} else {
None
};
self.enter(Some(Info {
name,
..Default::default()
}));
let mut index = 0;
while index < node.function.params.len() {
self.add_pat(&node.function.params[index].pat, false);
index += 1;
}
node.visit_mut_children_with(self);
self.exit_func(Func::Expr(node));
}
/// On arrow functions, create scope, add parameters.
fn visit_mut_arrow_expr(&mut self, node: &mut swc_ecma_ast::ArrowExpr) {
self.enter(Some(Info::default()));
let mut index = 0;
while index < node.params.len() {
self.add_pat(&node.params[index], false);
index += 1;
}
node.visit_mut_children_with(self);
self.exit_func(Func::Arrow(node));
}
// Blocks.
// Not sure why `periscopic` only does `For`/`ForIn`/`ForOf`/`Block`.
// I added `While`/`DoWhile` here just to be sure.
// But there are more.
/// On for statements, create scope.
fn visit_mut_for_stmt(&mut self, node: &mut swc_ecma_ast::ForStmt) {
self.enter(None);
node.visit_mut_children_with(self);
self.exit();
}
/// On for/in statements, create scope.
fn visit_mut_for_in_stmt(&mut self, node: &mut swc_ecma_ast::ForInStmt) {
self.enter(None);
node.visit_mut_children_with(self);
self.exit();
}
/// On for/of statements, create scope.
fn visit_mut_for_of_stmt(&mut self, node: &mut swc_ecma_ast::ForOfStmt) {
self.enter(None);
node.visit_mut_children_with(self);
self.exit();
}
/// On while statements, create scope.
fn visit_mut_while_stmt(&mut self, node: &mut swc_ecma_ast::WhileStmt) {
self.enter(None);
node.visit_mut_children_with(self);
self.exit();
}
/// On do/while statements, create scope.
fn visit_mut_do_while_stmt(&mut self, node: &mut swc_ecma_ast::DoWhileStmt) {
self.enter(None);
node.visit_mut_children_with(self);
self.exit();
}
/// On block statements, create scope.
fn visit_mut_block_stmt(&mut self, node: &mut swc_ecma_ast::BlockStmt) {
self.enter(None);
node.visit_mut_children_with(self);
self.exit();
}
/// On catch clauses, create scope, add param.
fn visit_mut_catch_clause(&mut self, node: &mut swc_ecma_ast::CatchClause) {
self.enter(None);
if let Some(pat) = &node.param {
self.add_pat(pat, true);
}
node.visit_mut_children_with(self);
self.exit();
}
}
/// Generate an import provider.
///
/// ```js
/// import { useMDXComponents as _provideComponents } from "x"
/// ```
fn create_import_provider(source: &str) -> swc_ecma_ast::ModuleItem {
swc_ecma_ast::ModuleItem::ModuleDecl(swc_ecma_ast::ModuleDecl::Import(
swc_ecma_ast::ImportDecl {
specifiers: vec![swc_ecma_ast::ImportSpecifier::Named(
swc_ecma_ast::ImportNamedSpecifier {
local: create_ident("_provideComponents"),
imported: Some(swc_ecma_ast::ModuleExportName::Ident(create_ident(
"useMDXComponents",
))),
span: swc_common::DUMMY_SP,
is_type_only: false,
},
)],
src: Box::new(swc_ecma_ast::Str {
value: source.into(),
span: swc_common::DUMMY_SP,
raw: None,
}),
type_only: false,
asserts: None,
span: swc_common::DUMMY_SP,
},
))
}
/// Generate an error helper.
///
/// ```js
/// function _missingMdxReference(id, component) {
/// throw new Error("Expected " + (component ? "component" : "object") + " `" + id + "` to be defined: you likely forgot to import, pass, or provide it.");
/// }
/// ```
fn create_error_helper() -> swc_ecma_ast::ModuleItem {
let parameters = vec![
swc_ecma_ast::Param {
pat: swc_ecma_ast::Pat::Ident(swc_ecma_ast::BindingIdent {
id: create_ident("id"),
type_ann: None,
}),
decorators: vec![],
span: swc_common::DUMMY_SP,
},
swc_ecma_ast::Param {
pat: swc_ecma_ast::Pat::Ident(swc_ecma_ast::BindingIdent {
id: create_ident("component"),
type_ann: None,
}),
decorators: vec![],
span: swc_common::DUMMY_SP,
},
];
let message = vec![
swc_ecma_ast::Expr::Lit(swc_ecma_ast::Lit::Str(swc_ecma_ast::Str {
value: "Expected ".into(),
span: swc_common::DUMMY_SP,
raw: None,
})),
// `component ? "component" : "object"`
swc_ecma_ast::Expr::Paren(swc_ecma_ast::ParenExpr {
expr: Box::new(swc_ecma_ast::Expr::Cond(swc_ecma_ast::CondExpr {
test: Box::new(create_ident_expression("component")),
cons: Box::new(swc_ecma_ast::Expr::Lit(swc_ecma_ast::Lit::Str(
swc_ecma_ast::Str {
value: "component".into(),
span: swc_common::DUMMY_SP,
raw: None,
},
))),
alt: Box::new(swc_ecma_ast::Expr::Lit(swc_ecma_ast::Lit::Str(
swc_ecma_ast::Str {
value: "object".into(),
span: swc_common::DUMMY_SP,
raw: None,
},
))),
span: swc_common::DUMMY_SP,
})),
span: swc_common::DUMMY_SP,
}),
swc_ecma_ast::Expr::Lit(swc_ecma_ast::Lit::Str(swc_ecma_ast::Str {
value: " `".into(),
span: swc_common::DUMMY_SP,
raw: None,
})),
create_ident_expression("id"),
swc_ecma_ast::Expr::Lit(swc_ecma_ast::Lit::Str(swc_ecma_ast::Str {
value: "` to be defined: you likely forgot to import, pass, or provide it.".into(),
span: swc_common::DUMMY_SP,
raw: None,
})),
];
// To do: in development, add `place` param, and use the positional info.
// Also, then, add file path.
swc_ecma_ast::ModuleItem::Stmt(swc_ecma_ast::Stmt::Decl(swc_ecma_ast::Decl::Fn(
swc_ecma_ast::FnDecl {
ident: create_ident("_missingMdxReference"),
declare: false,
function: Box::new(swc_ecma_ast::Function {
params: parameters,
decorators: vec![],
body: Some(swc_ecma_ast::BlockStmt {
stmts: vec![swc_ecma_ast::Stmt::Throw(swc_ecma_ast::ThrowStmt {
arg: Box::new(swc_ecma_ast::Expr::New(swc_ecma_ast::NewExpr {
callee: Box::new(create_ident_expression("Error")),
args: Some(vec![swc_ecma_ast::ExprOrSpread {
spread: None,
expr: Box::new(create_binary_expression(
message,
swc_ecma_ast::BinaryOp::Add,
)),
}]),
span: swc_common::DUMMY_SP,
type_args: None,
})),
span: swc_common::DUMMY_SP,
})],
span: swc_common::DUMMY_SP,
}),
is_generator: false,
is_async: false,
type_params: None,
return_type: None,
span: swc_common::DUMMY_SP,
}),
},
)))
}
/// Generate a binary expression.
///
/// ```js
/// a + b + c
/// a || b
/// ```
fn create_binary_expression(
mut exprs: Vec<swc_ecma_ast::Expr>,
op: swc_ecma_ast::BinaryOp,
) -> swc_ecma_ast::Expr {
exprs.reverse();
let mut left = None;
while let Some(right_expr) = exprs.pop() {
left = Some(if let Some(left_expr) = left {
swc_ecma_ast::Expr::Bin(swc_ecma_ast::BinExpr {
left: Box::new(left_expr),
right: Box::new(right_expr),
op,
span: swc_common::DUMMY_SP,
})
} else {
right_expr
});
}
left.expect("expected one or more expressions")
}
/// Generate a member expression.
///
/// ```js
/// a.b
/// a
/// ```
fn create_member_expression(name: &str) -> swc_ecma_ast::Expr {
let bytes = name.as_bytes();
let mut index = 0;
let mut start = 0;
let mut parts = vec![];
while index < bytes.len() {
if bytes[index] == b'.' {
parts.push(&name[start..index]);
start = index + 1;
}
index += 1;
}
if parts.len() > 1 {
let mut member = swc_ecma_ast::MemberExpr {
obj: Box::new(create_ident_expression(parts[0])),
prop: swc_ecma_ast::MemberProp::Ident(create_ident(parts[1])),
span: swc_common::DUMMY_SP,
};
let mut index = 2;
while index < parts.len() {
member = swc_ecma_ast::MemberExpr {
obj: Box::new(swc_ecma_ast::Expr::Member(member)),
prop: swc_ecma_ast::MemberProp::Ident(create_ident(parts[1])),
span: swc_common::DUMMY_SP,
};
index += 1;
}
swc_ecma_ast::Expr::Member(member)
} else {
create_ident_expression(name)
}
}
/// Generate an ident expression.
///
/// ```js
/// a
/// ```
fn create_ident_expression(sym: &str) -> swc_ecma_ast::Expr {
swc_ecma_ast::Expr::Ident(create_ident(sym))
}
/// Generate an ident.
///
/// ```js
/// a
/// ```
fn create_ident(sym: &str) -> swc_ecma_ast::Ident {
swc_ecma_ast::Ident {
sym: sym.into(),
optional: false,
span: swc_common::DUMMY_SP,
}
}
/// Check if this function is a props receiving component: it’s one of ours.
fn is_props_receiving_fn(name: &Option<String>) -> bool {
if let Some(name) = name {
name == "_createMdxContent" || name == "MDXContent"
} else {
false
}
}
/// Check if a name is a literal tag name or an identifier to a component.
fn is_literal_name(name: &str) -> bool {
matches!(name.as_bytes().first(), Some(b'a'..=b'z')) || !is_identifier_name(name)
}
// Check if a name is a valid identifier name.
fn is_identifier_name(name: &str) -> bool {
for (index, char) in name.chars().enumerate() {
if if index == 0 {
!id_start(char)
} else {
!id_cont(char)
} {
return false;
}
}
true
}
// To do: share with `partial_mdx_jsx`.
/// Check if a character can start a JS identifier.
fn id_start(char: char) -> bool {
UnicodeID::is_id_start(char) || matches!(char, '$' | '_')
}
// To do: share with `partial_mdx_jsx`.
/// Check if a character can continue a JS identifier.
fn id_cont(char: char) -> bool {
UnicodeID::is_id_continue(char) || matches!(char, '\u{200c}' | '\u{200d}')
}
|