-
-
Notifications
You must be signed in to change notification settings - Fork 619
/
Copy pathcompilation.rs
1697 lines (1531 loc) · 55.7 KB
/
compilation.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::{
collections::{hash_map, VecDeque},
fmt::Debug,
hash::{BuildHasherDefault, Hash},
path::PathBuf,
sync::Arc,
};
use dashmap::{DashMap, DashSet};
use indexmap::{IndexMap, IndexSet};
use itertools::Itertools;
use rayon::prelude::*;
use rspack_error::{error, Diagnostic, Result, Severity, TWithDiagnosticArray};
use rspack_futures::FuturesResults;
use rspack_hash::{RspackHash, RspackHashDigest};
use rspack_hook::{
AsyncSeries2Hook, AsyncSeries3Hook, AsyncSeriesBailHook, AsyncSeriesHook, SyncSeries4Hook,
};
use rspack_identifier::{Identifiable, Identifier, IdentifierMap, IdentifierSet};
use rspack_sources::{BoxSource, CachedSource, SourceExt};
use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet, FxHasher};
use swc_core::ecma::ast::ModuleItem;
use tracing::instrument;
use super::{
hmr::CompilationRecords,
make::{update_module_graph, MakeParam},
};
use crate::{
build_chunk_graph::build_chunk_graph,
cache::{use_code_splitting_cache, Cache, CodeSplittingCache},
get_chunk_from_ukey, get_mut_chunk_from_ukey, is_source_equal, prepare_get_exports_type,
to_identifier,
tree_shaking::{optimizer, visitor::SymbolRef, BailoutFlag, OptimizeDependencyResult},
AddQueueHandler, AdditionalChunkRuntimeRequirementsArgs, AdditionalModuleRequirementsArgs,
BoxDependency, BoxModule, BuildQueueHandler, BuildTimeExecutionQueueHandler, CacheCount,
CacheOptions, Chunk, ChunkByUkey, ChunkContentHash, ChunkGraph, ChunkGroupByUkey, ChunkGroupUkey,
ChunkHashArgs, ChunkKind, ChunkUkey, CodeGenerationResults, CompilationLogger,
CompilationLogging, CompilerOptions, ContentHashArgs, DependencyId, DependencyType, Entry,
EntryData, EntryOptions, Entrypoint, ErrorSpan, FactorizeQueueHandler, Filename, ImportVarMap,
LocalFilenameFn, Logger, Module, ModuleFactory, ModuleGraph, ModuleGraphPartial,
ModuleIdentifier, PathData, ProcessDependenciesQueueHandler, RenderManifestArgs, ResolverFactory,
RuntimeGlobals, RuntimeModule, RuntimeRequirementsInTreeArgs, RuntimeSpec, SharedPluginDriver,
SourceType, Stats,
};
use crate::{tree_shaking::visitor::OptimizeAnalyzeResult, ExecuteModuleId};
pub type BuildDependency = (
DependencyId,
Option<ModuleIdentifier>, /* parent module */
);
pub type CompilationBuildModuleHook = AsyncSeriesHook<BoxModule>;
pub type CompilationStillValidModuleHook = AsyncSeriesHook<BoxModule>;
pub type CompilationSucceedModuleHook = AsyncSeriesHook<BoxModule>;
pub type CompilationExecuteModuleHook =
SyncSeries4Hook<ModuleIdentifier, IdentifierSet, CodeGenerationResults, ExecuteModuleId>;
pub type CompilationFinishModulesHook = AsyncSeriesHook<Compilation>;
pub type CompilationOptimizeModulesHook = AsyncSeriesBailHook<Compilation, bool>;
pub type CompilationAfterOptimizeModulesHook = AsyncSeriesHook<Compilation>;
pub type CompilationOptimizeTreeHook = AsyncSeriesHook<Compilation>;
pub type CompilationOptimizeChunkModulesHook = AsyncSeriesBailHook<Compilation, bool>;
pub type CompilationRuntimeModuleHook = AsyncSeries3Hook<Compilation, ModuleIdentifier, ChunkUkey>;
pub type CompilationChunkAssetHook = AsyncSeries2Hook<Chunk, String>;
pub type CompilationProcessAssetsHook = AsyncSeriesHook<Compilation>;
pub type CompilationAfterProcessAssetsHook = AsyncSeriesHook<Compilation>;
#[derive(Debug, Default)]
pub struct CompilationHooks {
pub build_module: CompilationBuildModuleHook,
pub still_valid_module: CompilationStillValidModuleHook,
pub succeed_module: CompilationSucceedModuleHook,
pub execute_module: CompilationExecuteModuleHook,
pub finish_modules: CompilationFinishModulesHook,
pub optimize_modules: CompilationOptimizeModulesHook,
pub after_optimize_modules: CompilationAfterOptimizeModulesHook,
pub optimize_tree: CompilationOptimizeTreeHook,
pub optimize_chunk_modules: CompilationOptimizeChunkModulesHook,
pub runtime_module: CompilationRuntimeModuleHook,
pub chunk_asset: CompilationChunkAssetHook,
pub process_assets: CompilationProcessAssetsHook,
pub after_process_assets: CompilationAfterProcessAssetsHook,
}
#[derive(Debug)]
pub struct Compilation {
// Mark compilation status, because the hash of `[hash].hot-update.js/json` is previous compilation hash.
// Status A(hash: A) -> Status B(hash: B) will generate `A.hot-update.js`
// Status A(hash: A) -> Status C(hash: C) will generate `A.hot-update.js`
// The status is different, should generate different hash for `.hot-update.js`
// So use compilation hash update `hot_index` to fix it.
pub hot_index: u32,
pub records: Option<CompilationRecords>,
pub options: Arc<CompilerOptions>,
pub entries: Entry,
pub global_entry: EntryData,
make_module_graph: ModuleGraphPartial,
other_module_graph: Option<ModuleGraphPartial>,
dependency_factories: HashMap<DependencyType, Arc<dyn ModuleFactory>>,
pub make_failed_dependencies: HashSet<BuildDependency>,
pub make_failed_module: HashSet<ModuleIdentifier>,
pub has_module_import_export_change: bool,
pub runtime_modules: IdentifierMap<Box<dyn RuntimeModule>>,
pub runtime_module_code_generation_results: IdentifierMap<(RspackHashDigest, BoxSource)>,
pub chunk_graph: ChunkGraph,
pub chunk_by_ukey: ChunkByUkey,
pub chunk_group_by_ukey: ChunkGroupByUkey,
pub entrypoints: IndexMap<String, ChunkGroupUkey>,
pub async_entrypoints: Vec<ChunkGroupUkey>,
assets: CompilationAssets,
pub emitted_assets: DashSet<String, BuildHasherDefault<FxHasher>>,
diagnostics: Vec<Diagnostic>,
logging: CompilationLogging,
pub plugin_driver: SharedPluginDriver,
pub resolver_factory: Arc<ResolverFactory>,
pub loader_resolver_factory: Arc<ResolverFactory>,
pub named_chunks: HashMap<String, ChunkUkey>,
pub(crate) named_chunk_groups: HashMap<String, ChunkGroupUkey>,
pub entry_module_identifiers: IdentifierSet,
/// Collecting all used export symbol
pub used_symbol_ref: HashSet<SymbolRef>,
/// Collecting all module that need to skip in tree-shaking ast modification phase
pub bailout_module_identifiers: IdentifierMap<BailoutFlag>,
pub optimize_analyze_result_map: IdentifierMap<OptimizeAnalyzeResult>,
pub code_generation_results: CodeGenerationResults,
pub code_generated_modules: IdentifierSet,
pub cache: Arc<Cache>,
pub code_splitting_cache: CodeSplittingCache,
pub hash: Option<RspackHashDigest>,
// lazy compilation visit module
pub lazy_visit_modules: std::collections::HashSet<String>,
pub used_chunk_ids: HashSet<String>,
pub include_module_ids: IdentifierSet,
pub file_dependencies: IndexSet<PathBuf, BuildHasherDefault<FxHasher>>,
pub context_dependencies: IndexSet<PathBuf, BuildHasherDefault<FxHasher>>,
pub missing_dependencies: IndexSet<PathBuf, BuildHasherDefault<FxHasher>>,
pub build_dependencies: IndexSet<PathBuf, BuildHasherDefault<FxHasher>>,
pub side_effects_free_modules: IdentifierSet,
pub module_item_map: IdentifierMap<Vec<ModuleItem>>,
pub factorize_queue: Option<FactorizeQueueHandler>,
pub build_queue: Option<BuildQueueHandler>,
pub add_queue: Option<AddQueueHandler>,
pub process_dependencies_queue: Option<ProcessDependenciesQueueHandler>,
pub build_time_execution_queue: Option<BuildTimeExecutionQueueHandler>,
import_var_map: DashMap<ModuleIdentifier, ImportVarMap>,
}
impl Compilation {
pub const PROCESS_ASSETS_STAGE_ADDITIONAL: i32 = -2000;
pub const PROCESS_ASSETS_STAGE_PRE_PROCESS: i32 = -1000;
pub const PROCESS_ASSETS_STAGE_DERIVED: i32 = -200;
pub const PROCESS_ASSETS_STAGE_ADDITIONS: i32 = -100;
pub const PROCESS_ASSETS_STAGE_OPTIMIZE: i32 = 100;
pub const PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT: i32 = 200;
pub const PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY: i32 = 300;
pub const PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE: i32 = 400;
pub const PROCESS_ASSETS_STAGE_DEV_TOOLING: i32 = 500;
pub const PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE: i32 = 700;
pub const PROCESS_ASSETS_STAGE_SUMMARIZE: i32 = 1000;
pub const PROCESS_ASSETS_STAGE_OPTIMIZE_HASH: i32 = 2500;
pub const PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER: i32 = 3000;
pub const PROCESS_ASSETS_STAGE_ANALYSE: i32 = 4000;
pub const PROCESS_ASSETS_STAGE_REPORT: i32 = 5000;
#[allow(clippy::too_many_arguments)]
pub fn new(
options: Arc<CompilerOptions>,
plugin_driver: SharedPluginDriver,
resolver_factory: Arc<ResolverFactory>,
loader_resolver_factory: Arc<ResolverFactory>,
records: Option<CompilationRecords>,
cache: Arc<Cache>,
) -> Self {
let make_module_graph = ModuleGraphPartial::new(options.is_new_tree_shaking());
Self {
hot_index: 0,
records,
options,
make_module_graph,
other_module_graph: None,
dependency_factories: Default::default(),
make_failed_dependencies: HashSet::default(),
make_failed_module: HashSet::default(),
has_module_import_export_change: true,
runtime_modules: Default::default(),
runtime_module_code_generation_results: Default::default(),
chunk_by_ukey: Default::default(),
chunk_group_by_ukey: Default::default(),
entries: Default::default(),
global_entry: Default::default(),
chunk_graph: Default::default(),
entrypoints: Default::default(),
async_entrypoints: Default::default(),
assets: Default::default(),
emitted_assets: Default::default(),
diagnostics: Default::default(),
logging: Default::default(),
plugin_driver,
resolver_factory,
loader_resolver_factory,
named_chunks: Default::default(),
named_chunk_groups: Default::default(),
entry_module_identifiers: IdentifierSet::default(),
used_symbol_ref: HashSet::default(),
optimize_analyze_result_map: IdentifierMap::default(),
bailout_module_identifiers: IdentifierMap::default(),
code_generation_results: Default::default(),
code_generated_modules: Default::default(),
cache,
code_splitting_cache: Default::default(),
hash: None,
lazy_visit_modules: Default::default(),
used_chunk_ids: Default::default(),
file_dependencies: Default::default(),
context_dependencies: Default::default(),
missing_dependencies: Default::default(),
build_dependencies: Default::default(),
side_effects_free_modules: IdentifierSet::default(),
module_item_map: IdentifierMap::default(),
include_module_ids: IdentifierSet::default(),
factorize_queue: None,
build_queue: None,
add_queue: None,
process_dependencies_queue: None,
build_time_execution_queue: None,
import_var_map: DashMap::new(),
}
}
pub fn swap_make_module_graph(&mut self, other: &mut Compilation) {
std::mem::swap(&mut self.make_module_graph, &mut other.make_module_graph);
}
pub fn get_module_graph(&self) -> ModuleGraph {
if let Some(other_module_graph) = &self.other_module_graph {
ModuleGraph::new(vec![&self.make_module_graph, other_module_graph], None)
} else {
ModuleGraph::new(vec![&self.make_module_graph], None)
}
}
pub fn get_module_graph_mut(&mut self) -> ModuleGraph {
if let Some(other) = &mut self.other_module_graph {
ModuleGraph::new(vec![&self.make_module_graph], Some(other))
} else {
ModuleGraph::new(vec![], Some(&mut self.make_module_graph))
}
}
// TODO move out from compilation
pub fn get_import_var(&self, dep_id: &DependencyId) -> String {
let module_graph = self.get_module_graph();
let parent_module_id = module_graph
.get_parent_module(dep_id)
.expect("should have parent module");
let module_id = module_graph
.module_identifier_by_dependency_id(dep_id)
.copied();
let module_dep = module_graph
.dependency_by_id(dep_id)
.and_then(|dep| dep.as_module_dependency())
.expect("should be module dependency");
let user_request = to_identifier(module_dep.user_request());
let mut import_var_map_of_module = self.import_var_map.entry(*parent_module_id).or_default();
let len = import_var_map_of_module.len();
let import_var = match import_var_map_of_module.entry(module_id) {
hash_map::Entry::Occupied(occ) => occ.get().clone(),
hash_map::Entry::Vacant(vac) => {
let import_var = format!("{}__WEBPACK_IMPORTED_MODULE_{}__", user_request, len);
vac.insert(import_var.clone());
import_var
}
};
import_var
}
pub fn get_entry_runtime(&self, name: &String, options: Option<&EntryOptions>) -> RuntimeSpec {
let (_, runtime) = if let Some(options) = options {
((), options.runtime.as_ref())
} else {
match self.entries.get(name) {
Some(entry) => ((), entry.options.runtime.as_ref()),
None => return RuntimeSpec::from_iter([Arc::from(name.as_str())]),
}
};
// TODO: depend on https://github.com/webpack/webpack/blob/1f99ad6367f2b8a6ef17cce0e058f7a67fb7db18/lib/util/runtime.js#L33, we don't have that field now
runtime
.or(Some(name))
.map(|runtime| RuntimeSpec::from_iter([Arc::from(runtime.as_ref())]))
.unwrap_or_default()
}
pub fn add_entry(&mut self, entry: BoxDependency, options: EntryOptions) -> Result<()> {
let entry_id = *entry.id();
self.get_module_graph_mut().add_dependency(entry);
if let Some(name) = options.name.clone() {
if let Some(data) = self.entries.get_mut(&name) {
data.dependencies.push(entry_id);
data.options.merge(options)?;
} else {
let data = EntryData {
dependencies: vec![entry_id],
include_dependencies: vec![],
options,
};
self.entries.insert(name, data);
}
} else {
self.global_entry.dependencies.push(entry_id);
}
Ok(())
}
pub async fn add_include(&mut self, entry: BoxDependency, options: EntryOptions) -> Result<()> {
let entry_id = *entry.id();
self.get_module_graph_mut().add_dependency(entry);
if let Some(name) = options.name.clone() {
if let Some(data) = self.entries.get_mut(&name) {
data.include_dependencies.push(entry_id);
} else {
let data = EntryData {
dependencies: vec![],
include_dependencies: vec![entry_id],
options,
};
self.entries.insert(name, data);
}
} else {
self.global_entry.include_dependencies.push(entry_id);
}
update_module_graph(
self,
vec![MakeParam::ForceBuildDeps(HashSet::from_iter([(
entry_id, None,
)]))],
)
.await
}
pub fn update_asset(
&mut self,
filename: &str,
updater: impl FnOnce(BoxSource, AssetInfo) -> Result<(BoxSource, AssetInfo)>,
) -> Result<()> {
// Safety: we don't move anything from compilation
let assets = &mut self.assets;
let (new_source, new_info) = match assets.remove(filename) {
Some(CompilationAsset {
source: Some(source),
info,
}) => updater(source, info)?,
_ => {
return Err(error!(
"Called Compilation.updateAsset for not existing filename {filename}"
))
}
};
self.emit_asset(
filename.to_owned(),
CompilationAsset {
source: Some(new_source),
info: new_info,
},
);
Ok(())
}
pub fn emit_asset(&mut self, filename: String, asset: CompilationAsset) {
tracing::trace!("Emit asset {}", filename);
if let Some(mut original) = self.assets.remove(&filename)
&& let Some(original_source) = &original.source
&& let Some(asset_source) = asset.get_source()
{
let is_source_equal = is_source_equal(original_source, asset_source);
if !is_source_equal {
tracing::error!(
"Emit Duplicate Filename({}), is_source_equal: {:?}",
filename,
is_source_equal
);
self.push_diagnostic(
error!(
"Conflict: Multiple assets emit different content to the same filename {}{}",
filename,
// TODO: source file name
""
)
.into(),
);
self.assets.insert(filename, asset);
return;
}
original.info = asset.info;
self.assets.insert(filename, original);
} else {
self.assets.insert(filename, asset);
}
}
pub fn delete_asset(&mut self, filename: &str) {
if let Some(asset) = self.assets.remove(filename) {
if let Some(source_map) = asset.info.related.source_map {
self.delete_asset(&source_map);
}
self.chunk_by_ukey.iter_mut().for_each(|(_, chunk)| {
chunk.files.remove(filename);
chunk.auxiliary_files.remove(filename);
});
}
}
pub fn rename_asset(&mut self, filename: &str, new_name: String) {
if let Some(asset) = self.assets.remove(filename) {
self.assets.insert(new_name.clone(), asset);
self.chunk_by_ukey.iter_mut().for_each(|(_, chunk)| {
if chunk.files.remove(filename) {
chunk.files.insert(new_name.clone());
}
if chunk.auxiliary_files.remove(filename) {
chunk.auxiliary_files.insert(new_name.clone());
}
});
}
}
pub fn assets(&self) -> &CompilationAssets {
&self.assets
}
pub fn assets_mut(&mut self) -> &mut CompilationAssets {
&mut self.assets
}
pub fn entrypoints(&self) -> &IndexMap<String, ChunkGroupUkey> {
&self.entrypoints
}
pub fn push_diagnostic(&mut self, diagnostic: Diagnostic) {
self.diagnostics.push(diagnostic);
}
pub fn push_batch_diagnostic(&mut self, diagnostics: Vec<Diagnostic>) {
self.diagnostics.extend(diagnostics);
}
pub fn get_errors(&self) -> impl Iterator<Item = &Diagnostic> {
self
.diagnostics
.iter()
.filter(|d| matches!(d.severity(), Severity::Error))
}
/// Get sorted errors based on the factors as follows in order:
/// - module identifier
/// - error offset
/// Rspack assumes for each offset, there is only one error.
/// However, when it comes to the case that there are multiple errors with the same offset,
/// the order of these errors will not be guaranteed.
pub fn get_errors_sorted(&self) -> impl Iterator<Item = &Diagnostic> {
let get_offset = |d: &dyn rspack_error::miette::Diagnostic| {
d.labels()
.and_then(|mut l| l.next())
.map(|l| l.offset())
.unwrap_or_default()
};
self.get_errors().sorted_by(
|a, b| match a.module_identifier().cmp(&b.module_identifier()) {
std::cmp::Ordering::Equal => get_offset(a.as_ref()).cmp(&get_offset(b.as_ref())),
other => other,
},
)
}
pub fn get_warnings(&self) -> impl Iterator<Item = &Diagnostic> {
self
.diagnostics
.iter()
.filter(|d| matches!(d.severity(), Severity::Warn))
}
/// Get sorted warnings based on the factors as follows in order:
/// - module identifier
/// - error offset
/// Rspack assumes for each offset, there is only one error.
/// However, when it comes to the case that there are multiple errors with the same offset,
/// the order of these errors will not be guaranteed.
pub fn get_warnings_sorted(&self) -> impl Iterator<Item = &Diagnostic> {
let get_offset = |d: &dyn rspack_error::miette::Diagnostic| {
d.labels()
.and_then(|mut l| l.next())
.map(|l| l.offset())
.unwrap_or_default()
};
self.get_warnings().sorted_by(
|a, b| match a.module_identifier().cmp(&b.module_identifier()) {
std::cmp::Ordering::Equal => get_offset(a.as_ref()).cmp(&get_offset(b.as_ref())),
other => other,
},
)
}
pub fn get_logging(&self) -> &CompilationLogging {
&self.logging
}
pub fn get_stats(&self) -> Stats {
Stats::new(self)
}
pub fn add_named_chunk(
name: String,
chunk_by_ukey: &mut ChunkByUkey,
named_chunks: &mut HashMap<String, ChunkUkey>,
) -> ChunkUkey {
let existed_chunk_ukey = named_chunks.get(&name);
if let Some(chunk_ukey) = existed_chunk_ukey {
assert!(chunk_by_ukey.contains(chunk_ukey));
*chunk_ukey
} else {
let chunk = Chunk::new(Some(name.clone()), ChunkKind::Normal);
let ukey = chunk.ukey;
named_chunks.insert(name, chunk.ukey);
chunk_by_ukey.entry(ukey).or_insert_with(|| chunk);
ukey
}
}
pub fn add_chunk(chunk_by_ukey: &mut ChunkByUkey) -> ChunkUkey {
let chunk = Chunk::new(None, ChunkKind::Normal);
let ukey = chunk.ukey;
chunk_by_ukey.add(chunk);
ukey
}
#[instrument(name = "compilation:make", skip_all)]
pub async fn make(&mut self, mut params: Vec<MakeParam>) -> Result<()> {
let make_failed_module =
MakeParam::ForceBuildModules(std::mem::take(&mut self.make_failed_module));
let make_failed_dependencies =
MakeParam::ForceBuildDeps(std::mem::take(&mut self.make_failed_dependencies));
params.push(make_failed_module);
params.push(make_failed_dependencies);
update_module_graph(self, params).await
}
pub async fn rebuild_module<T>(
&mut self,
module_identifiers: HashSet<ModuleIdentifier>,
f: impl Fn(Vec<&BoxModule>) -> T,
) -> Result<T> {
for id in &module_identifiers {
self.cache.build_module_occasion.remove_cache(id);
}
update_module_graph(
self,
vec![MakeParam::ForceBuildModules(module_identifiers.clone())],
)
.await?;
if self.options.is_new_tree_shaking() {
let logger = self.get_logger("rspack.Compilation");
let start = logger.time("finish module");
self.finish(self.plugin_driver.clone()).await?;
logger.time_end(start);
}
let module_graph = self.get_module_graph();
Ok(f(module_identifiers
.into_iter()
.filter_map(|id| module_graph.module_by_identifier(&id))
.collect::<Vec<_>>()))
}
#[instrument(name = "compilation:code_generation", skip(self))]
fn code_generation(&mut self) -> Result<()> {
let logger = self.get_logger("rspack.Compilation");
let mut codegen_cache_counter = match self.options.cache {
CacheOptions::Disabled => None,
_ => Some(logger.cache("module code generation cache")),
};
fn run_iteration(
compilation: &mut Compilation,
codegen_cache_counter: &mut Option<CacheCount>,
filter_op: impl Fn(&(ModuleIdentifier, &Box<dyn Module>)) -> bool + Sync + Send,
) -> Result<()> {
// If the runtime optimization is not opt out, a module codegen should be executed for each runtime.
// Else, share same codegen result for all runtimes.
let used_exports_optimization = compilation.options.is_new_tree_shaking()
&& compilation.options.optimization.used_exports.is_true();
let results = compilation.code_generation_modules(
codegen_cache_counter,
used_exports_optimization,
compilation
.get_module_graph()
.modules()
.into_iter()
.filter(filter_op)
.map(|(id, _)| id)
.collect::<Vec<_>>()
.into_par_iter(),
)?;
results.iter().for_each(|module_identifier| {
compilation
.code_generated_modules
.insert(*module_identifier);
});
Ok(())
}
// FIXME:
// Webpack may modify the moduleGraph in module.getExportsType()
// and it is widely called after compilation.finish()
// so add this method to trigger moduleGraph modification and
// then make sure that moduleGraph is immutable
prepare_get_exports_type(&mut self.get_module_graph_mut());
run_iteration(self, &mut codegen_cache_counter, |(_, module)| {
module.get_code_generation_dependencies().is_none()
})?;
run_iteration(self, &mut codegen_cache_counter, |(_, module)| {
module.get_code_generation_dependencies().is_some()
})?;
if let Some(counter) = codegen_cache_counter {
logger.cache_end(counter);
}
Ok(())
}
pub(crate) fn code_generation_modules(
&mut self,
codegen_cache_counter: &mut Option<CacheCount>,
used_exports_optimization: bool,
modules: impl ParallelIterator<Item = ModuleIdentifier>,
) -> Result<Vec<ModuleIdentifier>> {
let chunk_graph = &self.chunk_graph;
let module_graph = self.get_module_graph();
#[allow(clippy::type_complexity)]
let results = modules
.filter_map(|module_identifier| {
let runtimes = chunk_graph.get_module_runtimes(module_identifier, &self.chunk_by_ukey);
if runtimes.is_empty() {
return None;
}
let module = module_graph
.module_by_identifier(&module_identifier)
.expect("module should exist");
let res = self
.cache
.code_generate_occasion
.use_cache(module, runtimes, self, |module, runtimes| {
let take_length = if used_exports_optimization {
runtimes.len()
} else {
// Only codegen once
1
};
let mut codegen_list = vec![];
for runtime in runtimes.into_values().take(take_length) {
codegen_list.push((module.code_generation(self, Some(&runtime), None)?, runtime));
}
Ok(codegen_list)
})
.map(|(result, from_cache)| (module_identifier, result, from_cache));
Some(res)
})
.collect::<Result<Vec<_>>>()?;
let results = results
.into_iter()
.map(|(module_identifier, item, from_cache)| {
item.into_iter().for_each(|(result, runtime)| {
if let Some(counter) = codegen_cache_counter {
if from_cache {
counter.hit();
} else {
counter.miss();
}
}
let runtimes = chunk_graph.get_module_runtimes(module_identifier, &self.chunk_by_ukey);
let result_id = result.id;
self
.code_generation_results
.module_generation_result_map
.insert(result.id, result);
if used_exports_optimization {
self
.code_generation_results
.add(module_identifier, runtime, result_id);
} else {
for runtime in runtimes.into_values() {
self
.code_generation_results
.add(module_identifier, runtime, result_id);
}
}
});
module_identifier
});
Ok(results.collect())
}
#[instrument(name = "compilation::create_module_assets", skip_all)]
async fn create_module_assets(&mut self, _plugin_driver: SharedPluginDriver) {
let mut temp = vec![];
for (module_identifier, module) in self.get_module_graph().modules() {
if let Some(build_info) = module.build_info() {
for asset in build_info.asset_filenames.iter() {
for chunk in self.chunk_graph.get_module_chunks(module_identifier).iter() {
temp.push((*chunk, asset.clone()))
}
// already emitted asset by loader, so no need to re emit here
}
}
}
for (chunk, asset) in temp {
let chunk = self.chunk_by_ukey.expect_get_mut(&chunk);
chunk.auxiliary_files.insert(asset);
}
}
#[instrument(skip_all)]
async fn create_chunk_assets(&mut self, plugin_driver: SharedPluginDriver) {
let results = self
.chunk_by_ukey
.values()
.map(|chunk| async {
let manifest_result = plugin_driver
.render_manifest(RenderManifestArgs {
chunk_ukey: chunk.ukey,
compilation: self,
})
.await;
if let Ok(manifest) = &manifest_result {
tracing::debug!(
"For Chunk({:?}), collected assets: {:?}",
chunk.id,
manifest
.inner
.iter()
.map(|m| m.filename())
.collect::<Vec<_>>()
);
};
(chunk.ukey, manifest_result)
})
.collect::<FuturesResults<_>>();
let chunk_ukey_and_manifest = results.into_inner();
for (chunk_ukey, manifest_result) in chunk_ukey_and_manifest.into_iter() {
let (manifests, diagnostics) = manifest_result
.expect("We should return this error rathen expect")
.split_into_parts();
self.push_batch_diagnostic(diagnostics);
for file_manifest in manifests {
let filename = file_manifest.filename().to_string();
let current_chunk = self.chunk_by_ukey.expect_get_mut(&chunk_ukey);
if file_manifest.auxiliary {
current_chunk.auxiliary_files.insert(filename.clone());
} else {
current_chunk.files.insert(filename.clone());
}
self.emit_asset(
filename.clone(),
CompilationAsset::new(
Some(CachedSource::new(file_manifest.source).boxed()),
file_manifest.info,
),
);
_ = self
.chunk_asset(chunk_ukey, filename, plugin_driver.clone())
.await;
}
//
// .into_iter()
// .for_each(|file_manifest| {
// });
}
// .for_each(|(chunk_ukey, manifest)| {
// })
}
#[instrument(name = "compilation:after_process_asssets", skip_all)]
async fn after_process_assets(&mut self, plugin_driver: SharedPluginDriver) -> Result<()> {
plugin_driver
.compilation_hooks
.after_process_assets
.call(self)
.await
}
#[instrument(
name = "compilation:chunk_asset",
skip(self, plugin_driver, chunk_ukey)
)]
async fn chunk_asset(
&mut self,
chunk_ukey: ChunkUkey,
mut filename: String,
plugin_driver: SharedPluginDriver,
) -> Result<()> {
let current_chunk = self.chunk_by_ukey.expect_get_mut(&chunk_ukey);
plugin_driver
.compilation_hooks
.chunk_asset
.call(current_chunk, &mut filename)
.await?;
Ok(())
}
pub async fn optimize_dependency(
&mut self,
) -> Result<TWithDiagnosticArray<OptimizeDependencyResult>> {
let logger = self.get_logger("rspack.Compilation");
let start = logger.time("optimize dependencies");
let result = optimizer::CodeSizeOptimizer::new(self).run().await;
logger.time_end(start);
result
}
pub async fn done(&mut self, plugin_driver: SharedPluginDriver) -> Result<()> {
let stats = &mut Stats::new(self);
plugin_driver.done(stats).await?;
Ok(())
}
pub fn entry_modules(&self) -> impl Iterator<Item = ModuleIdentifier> {
self.entry_module_identifiers.clone().into_iter()
}
pub fn entrypoint_by_name(&self, name: &str) -> &Entrypoint {
let ukey = self.entrypoints.get(name).expect("entrypoint not found");
self.chunk_group_by_ukey.expect_get(ukey)
}
#[instrument(name = "compilation:finish", skip_all)]
pub async fn finish(&mut self, plugin_driver: SharedPluginDriver) -> Result<()> {
let logger = self.get_logger("rspack.Compilation");
let start = logger.time("finish modules");
plugin_driver
.compilation_hooks
.finish_modules
.call(self)
.await?;
logger.time_end(start);
Ok(())
}
#[instrument(name = "compilation:seal", skip_all)]
pub async fn seal(&mut self, plugin_driver: SharedPluginDriver) -> Result<()> {
self.other_module_graph = Some(ModuleGraphPartial::new(self.options.is_new_tree_shaking()));
let logger = self.get_logger("rspack.Compilation");
// https://github.com/webpack/webpack/blob/main/lib/Compilation.js#L2809
plugin_driver.seal(self)?;
let start = logger.time("optimize dependencies");
// https://github.com/webpack/webpack/blob/d15c73469fd71cf98734685225250148b68ddc79/lib/Compilation.js#L2812-L2814
while plugin_driver.optimize_dependencies(self).await?.is_some() {}
logger.time_end(start);
// if self.options.is_new_tree_shaking() {
// // let filter = |item: &str| ["config-provider"].iter().any(|pat| item.contains(pat));
// // debug_all_exports_info!(&self.module_graph, filter);
// }
let start = logger.time("create chunks");
use_code_splitting_cache(self, |compilation| async {
build_chunk_graph(compilation)?;
while matches!(
plugin_driver
.compilation_hooks
.optimize_modules
.call(compilation)
.await?,
Some(true)
) {}
plugin_driver
.compilation_hooks
.after_optimize_modules
.call(compilation)
.await?;
plugin_driver.optimize_chunks(compilation).await?;
Ok(compilation)
})
.await?;
logger.time_end(start);
let start = logger.time("optimize");
plugin_driver
.compilation_hooks
.optimize_tree
.call(self)
.await?;
plugin_driver
.compilation_hooks
.optimize_chunk_modules
.call(self)
.await?;
logger.time_end(start);
let start = logger.time("module ids");
plugin_driver.module_ids(self)?;
logger.time_end(start);
let start = logger.time("chunk ids");
plugin_driver.chunk_ids(self)?;
logger.time_end(start);
self.assign_runtime_ids();
let start = logger.time("optimize code generation");
plugin_driver.optimize_code_generation(self).await?;
logger.time_end(start);
let start = logger.time("code generation");
self.code_generation()?;
logger.time_end(start);
let start = logger.time("runtime requirements");
self
.process_runtime_requirements(
self
.get_module_graph()
.modules()
.keys()
.copied()
.collect::<Vec<_>>(),
self
.chunk_by_ukey
.keys()
.copied()
.collect::<Vec<_>>()
.into_iter(),
self.get_chunk_graph_entries().into_iter(),
plugin_driver.clone(),
)
.await?;
logger.time_end(start);
let start = logger.time("hashing");
self.create_hash(plugin_driver.clone()).await?;
logger.time_end(start);
let start = logger.time("create module assets");
self.create_module_assets(plugin_driver.clone()).await;
logger.time_end(start);
let start = logger.time("create chunk assets");
self.create_chunk_assets(plugin_driver.clone()).await;
logger.time_end(start);
let start = logger.time("process assets");
plugin_driver
.compilation_hooks
.process_assets
.call(self)
.await?;
logger.time_end(start);
let start = logger.time("after process assets");
self.after_process_assets(plugin_driver).await?;
logger.time_end(start);
Ok(())
}
pub fn assign_runtime_ids(&mut self) {