/
graph.rs
1059 lines (931 loc) · 39.3 KB
/
graph.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
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
use std::{
fmt,
hash::{BuildHasherDefault, Hash},
};
use indexmap::IndexSet;
use petgraph::{
algo::{has_path_connecting, kosaraju_scc},
prelude::DiGraphMap,
};
use rustc_hash::{FxHashMap, FxHashSet, FxHasher};
use swc_core::{
common::{util::take::Take, SyntaxContext, DUMMY_SP},
ecma::{
ast::{
op, ClassDecl, Decl, DefaultDecl, ExportDecl, ExportNamedSpecifier, ExportSpecifier,
Expr, ExprStmt, FnDecl, Id, Ident, ImportDecl, ImportNamedSpecifier, ImportSpecifier,
ImportStarAsSpecifier, KeyValueProp, Lit, Module, ModuleDecl, ModuleExportName,
ModuleItem, NamedExport, ObjectLit, Prop, PropName, PropOrSpread, Stmt, VarDecl,
},
atoms::JsWord,
utils::{find_pat_ids, private_ident, quote_ident, IdentExt},
},
};
use super::{
util::{ids_captured_by, ids_used_by, ids_used_by_ignoring_nested},
Key,
};
use crate::magic_identifier;
/// The id of an item
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum ItemId {
Group(ItemIdGroupKind),
Item { index: usize, kind: ItemIdItemKind },
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum ItemIdGroupKind {
ModuleEvaluation,
/// `(local, export_name)``
Export(Id, JsWord),
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum ItemIdItemKind {
Normal,
ImportOfModule,
/// Imports are split as multiple items.
ImportBinding(u32),
VarDeclarator(u32),
}
impl fmt::Debug for ItemId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ItemId::Group(kind) => {
write!(f, "ItemId({:?})", kind)
}
ItemId::Item { index, kind } => {
write!(f, "ItemId({}, {:?})", index, kind)
}
}
}
}
type FxBuildHasher = BuildHasherDefault<FxHasher>;
/// Data about a module item
#[derive(Debug)]
pub(crate) struct ItemData {
/// Is the module item hoisted?
pub is_hoisted: bool,
pub pure: bool,
/// Variables declared or bound by this module item
pub var_decls: IndexSet<Id, FxBuildHasher>,
/// Variables read by this module item during evaluation
pub read_vars: IndexSet<Id, FxBuildHasher>,
/// Variables read by this module item eventually
///
/// - e.g. variables read in the body of function declarations are
/// considered as eventually read
/// - This is only used when reads are not trigger directly by this module
/// item, but require a side effect to be triggered. We don’t know when
/// this is executed.
/// - Note: This doesn’t mean they are only read “after” initial evaluation.
/// They might also be read “during” initial evaluation on any module item
/// with SIDE_EFFECTS. This kind of interaction is handled by the module
/// item with SIDE_EFFECTS.
pub eventual_read_vars: IndexSet<Id, FxBuildHasher>,
/// Side effects that are triggered on local variables during evaluation
pub write_vars: IndexSet<Id, FxBuildHasher>,
/// Side effects that are triggered on local variables eventually
pub eventual_write_vars: IndexSet<Id, FxBuildHasher>,
/// Any other unknown side effects that are trigger during evaluation
pub side_effects: bool,
pub content: ModuleItem,
pub export: Option<JsWord>,
}
impl Default for ItemData {
fn default() -> Self {
Self {
is_hoisted: Default::default(),
var_decls: Default::default(),
read_vars: Default::default(),
eventual_read_vars: Default::default(),
write_vars: Default::default(),
eventual_write_vars: Default::default(),
side_effects: Default::default(),
content: ModuleItem::dummy(),
pure: Default::default(),
export: Default::default(),
}
}
}
#[derive(Debug, Clone)]
pub struct InternedGraph<T>
where
T: Eq + Hash + Clone,
{
pub(super) idx_graph: DiGraphMap<u32, Dependency>,
pub(super) graph_ix: IndexSet<T, BuildHasherDefault<FxHasher>>,
}
#[derive(Debug, Clone, Copy)]
pub enum Dependency {
Strong,
Weak,
}
impl<T> Default for InternedGraph<T>
where
T: Eq + Hash + Clone,
{
fn default() -> Self {
Self {
idx_graph: Default::default(),
graph_ix: Default::default(),
}
}
}
impl<T> InternedGraph<T>
where
T: Eq + Hash + Clone,
{
pub(super) fn node(&mut self, id: &T) -> u32 {
self.graph_ix.get_index_of(id).unwrap_or_else(|| {
let ix = self.graph_ix.len();
self.graph_ix.insert_full(id.clone());
ix
}) as _
}
/// Panics if `id` is not found.
pub(super) fn get_node(&self, id: &T) -> u32 {
self.graph_ix.get_index_of(id).unwrap() as _
}
}
#[derive(Debug, Clone, Default)]
pub struct DepGraph {
pub(super) g: InternedGraph<ItemId>,
}
#[derive(Debug, Clone, Copy)]
pub(super) enum Mode {
#[allow(dead_code)]
Development,
Production,
}
pub(super) struct SplitModuleResult {
pub entrypoints: FxHashMap<Key, u32>,
pub uri_of_module: JsWord,
/// Dependency between parts.
pub part_deps: FxHashMap<u32, Vec<u32>>,
pub modules: Vec<Module>,
}
impl DepGraph {
/// Weak imports are imports only if it is referenced strongly. But this
/// is production-only, and weak dependencies are treated as strong
/// dependencies in development mode.
pub(super) fn handle_weak(&mut self, mode: Mode) {
if !matches!(mode, Mode::Production) {
return;
}
for start in self.g.graph_ix.iter() {
let start = self.g.get_node(start);
for end in self.g.graph_ix.iter() {
let end = self.g.get_node(end);
if let Some(Dependency::Weak) = self.g.idx_graph.edge_weight(start, end) {
self.g.idx_graph.remove_edge(start, end);
}
}
}
}
/// Split modules into parts. Additionally, this function adds imports to
/// _connect_ variables.
///
/// _connect_ here means if a variable is declared in a different part than
/// a usage side, `import` and `export` will be added.
///
/// Note: ESM imports are immutable, but we do not handle it.
pub(super) fn split_module(
&self,
uri_of_module: &JsWord,
data: &FxHashMap<ItemId, ItemData>,
) -> SplitModuleResult {
let groups = self.finalize(data);
let mut exports = FxHashMap::default();
let mut part_deps = FxHashMap::<_, Vec<_>>::default();
let mut modules = vec![];
if groups.graph_ix.is_empty() {
// If there's no dependency, all nodes are in the module evaluaiotn group.
modules.push(Module {
span: DUMMY_SP,
body: data.values().map(|v| v.content.clone()).collect(),
shebang: None,
});
exports.insert(Key::ModuleEvaluation, 0);
}
for (ix, group) in groups.graph_ix.iter().enumerate() {
let mut chunk = Module {
span: DUMMY_SP,
body: vec![],
shebang: None,
};
let mut required_vars = group
.iter()
.flat_map(|id| {
let data = data.get(id).unwrap();
data.read_vars
.iter()
.chain(data.write_vars.iter())
.chain(data.eventual_read_vars.iter())
.chain(data.eventual_write_vars.iter())
})
.collect::<FxHashSet<_>>();
for item in group {
match item {
ItemId::Group(ItemIdGroupKind::Export(id, _)) => {
required_vars.insert(id);
if let Some(export) = &data[item].export {
exports.insert(Key::Export(export.to_string()), ix as u32);
}
}
ItemId::Group(ItemIdGroupKind::ModuleEvaluation) => {
exports.insert(Key::ModuleEvaluation, ix as u32);
}
_ => {}
}
}
for dep in groups
.idx_graph
.neighbors_directed(ix as u32, petgraph::Direction::Outgoing)
{
let mut specifiers = vec![];
let deps = groups.graph_ix.get_index(dep as usize).unwrap();
for dep in deps {
let data = data.get(dep).unwrap();
for var in data.var_decls.iter().chain(data.write_vars.iter()) {
if required_vars.remove(var) {
specifiers.push(ImportSpecifier::Named(ImportNamedSpecifier {
span: DUMMY_SP,
local: var.clone().into(),
imported: None,
is_type_only: false,
}));
}
}
}
part_deps.entry(ix as u32).or_default().push(dep);
chunk
.body
.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
span: DUMMY_SP,
specifiers,
src: Box::new(uri_of_module.clone().into()),
type_only: false,
with: Some(Box::new(create_turbopack_chunk_id_assert(dep))),
phase: Default::default(),
})));
}
for g in group {
chunk.body.push(data[g].content.clone());
}
for g in group {
let data = data.get(g).unwrap();
// Emit `export { foo }`
for var in data.write_vars.iter() {
if required_vars.remove(var) {
let assertion_prop =
PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: quote_ident!("__turbopack_var__").into(),
value: Box::new(true.into()),
})));
chunk
.body
.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(
NamedExport {
span: DUMMY_SP,
specifiers: vec![ExportSpecifier::Named(
ExportNamedSpecifier {
span: DUMMY_SP,
orig: ModuleExportName::Ident(var.clone().into()),
exported: None,
is_type_only: false,
},
)],
src: None,
type_only: false,
with: Some(Box::new(ObjectLit {
span: DUMMY_SP,
props: vec![assertion_prop],
})),
},
)));
}
}
}
modules.push(chunk);
}
SplitModuleResult {
entrypoints: exports,
part_deps,
uri_of_module: uri_of_module.clone(),
modules,
}
}
/// Merges a dependency group between [ModuleItem]s into a dependency graph
/// of [Module]s.
///
/// Note that [ModuleItem] and [Module] are represented as [ItemId] for
/// performance.
pub(super) fn finalize(
&self,
data: &FxHashMap<ItemId, ItemData>,
) -> InternedGraph<Vec<ItemId>> {
/// Returns true if it should be called again
fn add_to_group(
graph: &InternedGraph<ItemId>,
data: &FxHashMap<ItemId, ItemData>,
group: &mut Vec<ItemId>,
start_ix: u32,
global_done: &mut FxHashSet<u32>,
group_done: &mut FxHashSet<u32>,
) -> bool {
let mut changed = false;
// Check deps of `start`.
for dep_ix in graph
.idx_graph
.neighbors_directed(start_ix, petgraph::Direction::Outgoing)
{
let dep_id = graph.graph_ix.get_index(dep_ix as _).unwrap().clone();
if global_done.insert(dep_ix)
|| (data.get(&dep_id).map_or(false, |data| data.pure)
&& group_done.insert(dep_ix))
{
changed = true;
group.push(dep_id);
add_to_group(graph, data, group, dep_ix, global_done, group_done);
}
}
changed
}
let mut cycles = kosaraju_scc(&self.g.idx_graph);
cycles.retain(|v| v.len() > 1);
// If a node have two or more dependents, it should be in a separate
// group.
let mut groups = vec![];
let mut global_done = FxHashSet::default();
// Module evaluation node and export nodes starts a group
for id in self.g.graph_ix.iter() {
let ix = self.g.get_node(id);
if let ItemId::Group(_) = id {
groups.push((vec![id.clone()], FxHashSet::default()));
global_done.insert(ix);
}
}
// Cycles should form a separate group
for id in self.g.graph_ix.iter() {
let ix = self.g.get_node(id);
if let Some(cycle) = cycles.iter().find(|v| v.contains(&ix)) {
if cycle.iter().all(|v| !global_done.contains(v)) {
let ids = cycle
.iter()
.map(|&ix| self.g.graph_ix[ix as usize].clone())
.collect::<Vec<_>>();
global_done.extend(cycle.iter().copied());
groups.push((ids, Default::default()));
}
}
}
// Expand **starting** nodes
for (ix, id) in self.g.graph_ix.iter().enumerate() {
// If a node is reachable from two or more nodes, it should be in a
// separate group.
if global_done.contains(&(ix as u32)) {
continue;
}
// Don't store a pure item in a separate chunk
if data.get(id).map_or(false, |data| data.pure) {
continue;
}
let count = global_done
.iter()
.filter(|&&staring_point| {
has_path_connecting(&self.g.idx_graph, staring_point, ix as _, None)
})
.count();
if count >= 2 {
groups.push((vec![id.clone()], FxHashSet::default()));
global_done.insert(ix as u32);
}
}
loop {
let mut changed = false;
for (group, group_done) in &mut groups {
let start = group[0].clone();
let start_ix = self.g.get_node(&start);
changed |=
add_to_group(&self.g, data, group, start_ix, &mut global_done, group_done);
}
if !changed {
break;
}
}
let mut groups = groups.into_iter().map(|v| v.0).collect::<Vec<_>>();
// We need to sort, because we start from the group item and add others start
// from them. But the final module should be in the order of the original code.
for group in groups.iter_mut() {
group.sort();
group.dedup();
}
let mut new_graph = InternedGraph::default();
let mut group_ix_by_item_ix = FxHashMap::default();
for group in &groups {
let group_ix = new_graph.node(group);
for item in group {
let item_ix = self.g.get_node(item);
group_ix_by_item_ix.insert(item_ix, group_ix);
}
}
for group in &groups {
let group_ix = new_graph.node(group);
for item in group {
let item_ix = self.g.get_node(item);
for item_dep_ix in self
.g
.idx_graph
.neighbors_directed(item_ix, petgraph::Direction::Outgoing)
{
let dep_group_ix = group_ix_by_item_ix.get(&item_dep_ix);
if let Some(&dep_group_ix) = dep_group_ix {
if group_ix == dep_group_ix {
continue;
}
new_graph
.idx_graph
.add_edge(group_ix, dep_group_ix, Dependency::Strong);
}
}
}
}
new_graph
}
/// Fills information per module items
pub(super) fn init(
&mut self,
module: &Module,
unresolved_ctxt: SyntaxContext,
) -> (Vec<ItemId>, FxHashMap<ItemId, ItemData>) {
let mut exports = vec![];
let mut items = FxHashMap::default();
let mut ids = vec![];
for (index, item) in module.body.iter().enumerate() {
// Fill exports
if let ModuleItem::ModuleDecl(item) = item {
match item {
ModuleDecl::ExportDecl(item) => match &item.decl {
Decl::Fn(FnDecl { ident, .. }) | Decl::Class(ClassDecl { ident, .. }) => {
exports.push((ident.to_id(), None));
}
Decl::Var(v) => {
for decl in &v.decls {
let ids: Vec<Id> = find_pat_ids(&decl.name);
for id in ids {
exports.push((id, None));
}
}
}
_ => {}
},
ModuleDecl::ExportNamed(item) => {
if let Some(src) = &item.src {
// One item for the import for re-export
let id = ItemId::Item {
index,
kind: ItemIdItemKind::ImportOfModule,
};
ids.push(id.clone());
items.insert(
id,
ItemData {
is_hoisted: true,
side_effects: true,
content: ModuleItem::ModuleDecl(ModuleDecl::Import(
ImportDecl {
specifiers: Default::default(),
src: src.clone(),
..ImportDecl::dummy()
},
)),
..Default::default()
},
);
}
for (si, s) in item.specifiers.iter().enumerate() {
let (orig, mut local, exported) = match s {
ExportSpecifier::Named(s) => (
Some(s.orig.clone()),
match s.exported.as_ref().unwrap_or(&s.orig) {
ModuleExportName::Ident(i) => i.clone(),
ModuleExportName::Str(..) => quote_ident!("_tmp"),
},
s.exported.clone(),
),
ExportSpecifier::Default(s) => (
Some(ModuleExportName::Ident(Ident::new(
"default".into(),
DUMMY_SP,
))),
quote_ident!("default"),
Some(ModuleExportName::Ident(s.exported.clone())),
),
ExportSpecifier::Namespace(s) => (
None,
match &s.name {
ModuleExportName::Ident(i) => i.clone(),
ModuleExportName::Str(..) => quote_ident!("_tmp"),
},
Some(s.name.clone()),
),
};
if item.src.is_some() {
local.sym =
magic_identifier::mangle(&format!("reexport {}", local.sym))
.into();
local = local.private();
}
exports.push((local.to_id(), exported.clone()));
if let Some(src) = &item.src {
let id = ItemId::Item {
index,
kind: ItemIdItemKind::ImportBinding(si as _),
};
ids.push(id.clone());
let import = match s {
ExportSpecifier::Namespace(..) => {
ImportSpecifier::Namespace(ImportStarAsSpecifier {
span: DUMMY_SP,
local: local.clone(),
})
}
_ => ImportSpecifier::Named(ImportNamedSpecifier {
span: DUMMY_SP,
local: local.clone(),
imported: orig,
is_type_only: false,
}),
};
items.insert(
id,
ItemData {
is_hoisted: true,
var_decls: [local.to_id()].into_iter().collect(),
pure: true,
content: ModuleItem::ModuleDecl(ModuleDecl::Import(
ImportDecl {
span: DUMMY_SP,
specifiers: vec![import],
src: src.clone(),
type_only: false,
with: None,
phase: Default::default(),
},
)),
..Default::default()
},
);
}
}
}
ModuleDecl::ExportDefaultDecl(export) => {
let id = match &export.decl {
DefaultDecl::Class(c) => c.ident.clone(),
DefaultDecl::Fn(f) => f.ident.clone(),
DefaultDecl::TsInterfaceDecl(_) => unreachable!(),
};
let default_var = id.unwrap_or_else(|| {
private_ident!(magic_identifier::mangle("default export"))
});
{
let used_ids = ids_used_by_ignoring_nested(&export.decl);
let captured_ids = ids_captured_by(&export.decl);
let data = ItemData {
read_vars: used_ids.read,
eventual_read_vars: captured_ids.read,
write_vars: used_ids.write,
eventual_write_vars: captured_ids.write,
var_decls: [default_var.to_id()].into_iter().collect(),
side_effects: true,
content: ModuleItem::ModuleDecl(item.clone()),
..Default::default()
};
let id = ItemId::Item {
index,
kind: ItemIdItemKind::Normal,
};
ids.push(id.clone());
items.insert(id, data);
}
exports.push((
default_var.to_id(),
Some(ModuleExportName::Ident(quote_ident!("default"))),
));
}
ModuleDecl::ExportDefaultExpr(export) => {
let default_var =
private_ident!(magic_identifier::mangle("default export"));
{
let used_ids = ids_used_by_ignoring_nested(&export.expr);
let captured_ids = ids_captured_by(&export.expr);
let data = ItemData {
read_vars: used_ids.read,
eventual_read_vars: captured_ids.read,
write_vars: used_ids.write,
eventual_write_vars: captured_ids.write,
var_decls: [default_var.to_id()].into_iter().collect(),
side_effects: true,
content: ModuleItem::ModuleDecl(item.clone()),
..Default::default()
};
let id = ItemId::Item {
index,
kind: ItemIdItemKind::Normal,
};
ids.push(id.clone());
items.insert(id, data);
}
exports.push((
default_var.to_id(),
Some(ModuleExportName::Ident(quote_ident!("default"))),
));
}
ModuleDecl::ExportAll(item) => {
// One item for the import for re-export
let id = ItemId::Item {
index,
kind: ItemIdItemKind::ImportOfModule,
};
ids.push(id.clone());
items.insert(
id,
ItemData {
is_hoisted: true,
side_effects: true,
content: ModuleItem::ModuleDecl(ModuleDecl::ExportAll(
item.clone(),
)),
..Default::default()
},
);
}
_ => {}
}
}
match item {
ModuleItem::ModuleDecl(ModuleDecl::Import(item)) => {
// We create multiple items for each import.
{
// One item for the import itself
let id = ItemId::Item {
index,
kind: ItemIdItemKind::ImportOfModule,
};
ids.push(id.clone());
items.insert(
id,
ItemData {
is_hoisted: true,
side_effects: true,
content: ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
specifiers: Default::default(),
..item.clone()
})),
..Default::default()
},
);
}
// One per binding
for (si, s) in item.specifiers.iter().enumerate() {
let id = ItemId::Item {
index,
kind: ItemIdItemKind::ImportBinding(si as _),
};
ids.push(id.clone());
let local = match s {
ImportSpecifier::Named(s) => s.local.to_id(),
ImportSpecifier::Default(s) => s.local.to_id(),
ImportSpecifier::Namespace(s) => s.local.to_id(),
};
items.insert(
id,
ItemData {
is_hoisted: true,
var_decls: [local].into_iter().collect(),
pure: true,
content: ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
specifiers: vec![s.clone()],
..item.clone()
})),
..Default::default()
},
);
}
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
decl: Decl::Fn(f),
..
}))
| ModuleItem::Stmt(Stmt::Decl(Decl::Fn(f))) => {
let id = ItemId::Item {
index,
kind: ItemIdItemKind::Normal,
};
ids.push(id.clone());
let vars = ids_used_by(&f.function);
items.insert(
id,
ItemData {
is_hoisted: true,
eventual_read_vars: vars.read,
eventual_write_vars: vars.write,
var_decls: {
let mut v =
IndexSet::with_capacity_and_hasher(1, Default::default());
v.insert(f.ident.to_id());
v
},
content: ModuleItem::Stmt(Stmt::Decl(Decl::Fn(f.clone()))),
..Default::default()
},
);
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
decl: Decl::Var(v),
..
}))
| ModuleItem::Stmt(Stmt::Decl(Decl::Var(v))) => {
for (i, decl) in v.decls.iter().enumerate() {
let id = ItemId::Item {
index,
kind: ItemIdItemKind::VarDeclarator(i as _),
};
ids.push(id.clone());
let decl_ids: Vec<Id> = find_pat_ids(&decl.name);
let vars = ids_used_by_ignoring_nested(&decl.init);
let eventual_vars = ids_captured_by(&decl.init);
let var_decl = Box::new(VarDecl {
decls: vec![decl.clone()],
..*v.clone()
});
let content = ModuleItem::Stmt(Stmt::Decl(Decl::Var(var_decl)));
items.insert(
id,
ItemData {
var_decls: decl_ids.clone().into_iter().collect(),
read_vars: vars.read,
eventual_read_vars: eventual_vars.read,
write_vars: decl_ids.into_iter().chain(vars.write).collect(),
eventual_write_vars: eventual_vars.write,
content,
..Default::default()
},
);
}
}
ModuleItem::Stmt(Stmt::Expr(ExprStmt {
expr: box Expr::Assign(assign),
..
})) => {
let mut used_ids = ids_used_by_ignoring_nested(item);
let captured_ids = ids_captured_by(item);
if assign.op != op!("=") {
let extra_ids = ids_used_by_ignoring_nested(&assign.left);
used_ids.read.extend(extra_ids.read);
used_ids.write.extend(extra_ids.write);
}
let side_effects = used_ids
.read
.iter()
.chain(used_ids.write.iter())
.any(|id| id.1 == unresolved_ctxt);
let data = ItemData {
read_vars: used_ids.read,
eventual_read_vars: captured_ids.read,
write_vars: used_ids.write,
eventual_write_vars: captured_ids.write,
content: item.clone(),
side_effects,
..Default::default()
};
let id = ItemId::Item {
index,
kind: ItemIdItemKind::Normal,
};
ids.push(id.clone());
items.insert(id, data);
}
ModuleItem::ModuleDecl(
ModuleDecl::ExportDefaultDecl(..)
| ModuleDecl::ExportDefaultExpr(..)
| ModuleDecl::ExportNamed(NamedExport { src: Some(..), .. }),
) => {}
_ => {
// Default to normal
let used_ids = ids_used_by_ignoring_nested(item);
let captured_ids = ids_captured_by(item);
let data = ItemData {
read_vars: used_ids.read,
eventual_read_vars: captured_ids.read,
write_vars: used_ids.write,
eventual_write_vars: captured_ids.write,
side_effects: true,
content: item.clone(),
..Default::default()
};
let id = ItemId::Item {
index,
kind: ItemIdItemKind::Normal,
};
ids.push(id.clone());
items.insert(id, data);
}
}
}
{
// `module evaluation side effects` Node
let id = ItemId::Group(ItemIdGroupKind::ModuleEvaluation);
ids.push(id.clone());
items.insert(
id,
ItemData {
content: ModuleItem::Stmt(Stmt::Expr(ExprStmt {
span: DUMMY_SP,
expr: "module evaluation".into(),
})),
..Default::default()
},
);
}
for (local, export_name) in exports {
let name = match &export_name {
Some(ModuleExportName::Ident(v)) => v.to_id(),
_ => local.clone(),
};
let id = ItemId::Group(ItemIdGroupKind::Export(local.clone(), name.0.clone()));
ids.push(id.clone());
items.insert(
id.clone(),
ItemData {
content: ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport {
span: DUMMY_SP,
specifiers: vec![ExportSpecifier::Named(ExportNamedSpecifier {
span: DUMMY_SP,
orig: ModuleExportName::Ident(local.clone().into()),
exported: export_name,
is_type_only: false,
})],
src: None,
type_only: false,
with: None,
})),
export: Some(name.0),
..Default::default()
},
);
}
(ids, items)
}
pub(super) fn add_strong_deps<'a, T>(&mut self, from: &ItemId, to: T)
where