-
Notifications
You must be signed in to change notification settings - Fork 28.2k
/
Copy pathmod.rs
3669 lines (3470 loc) · 138 KB
/
mod.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
pub mod amd;
pub mod async_module;
pub mod cjs;
pub mod constant_condition;
pub mod constant_value;
pub mod dynamic_expression;
pub mod esm;
pub mod external_module;
pub mod ident;
pub mod member;
pub mod node;
pub mod pattern_mapping;
pub mod raw;
pub mod require_context;
pub mod type_issue;
pub mod typescript;
pub mod unreachable;
pub mod util;
pub mod worker;
use std::{borrow::Cow, collections::BTreeMap, future::Future, mem::take, ops::Deref, sync::Arc};
use anyhow::{bail, Result};
use constant_condition::{ConstantConditionCodeGen, ConstantConditionValue};
use constant_value::ConstantValueCodeGen;
use either::Either;
use indexmap::map::Entry;
use lazy_static::lazy_static;
use num_traits::Zero;
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use regex::Regex;
use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize};
use swc_core::{
atoms::Atom,
common::{
comments::{CommentKind, Comments},
errors::{DiagnosticId, Handler, HANDLER},
pass::AstNodePath,
source_map::SmallPos,
Globals, Span, Spanned, GLOBALS,
},
ecma::{
ast::*,
utils::IsDirective,
visit::{
fields::{AssignExprField, AssignTargetField, SimpleAssignTargetField},
AstParentKind, AstParentNodeRef, VisitAstPath, VisitWithAstPath,
},
},
};
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{
trace::TraceRawVcs, FxIndexMap, FxIndexSet, NonLocalValue, ReadRef, ResolvedVc, TaskInput,
TryJoinIterExt, Upcast, Value, ValueToString, Vc,
};
use turbo_tasks_fs::{rope::Rope, FileSystemPath};
use turbopack_core::{
compile_time_info::{
CompileTimeInfo, DefineableNameSegment, FreeVarReference, FreeVarReferences,
FreeVarReferencesIndividual,
},
environment::Rendering,
error::PrettyPrintError,
issue::{analyze::AnalyzeIssue, IssueExt, IssueSeverity, IssueSource, StyledString},
module::Module,
reference::{ModuleReference, ModuleReferences, SourceMapReference},
reference_type::{CommonJsReferenceSubType, ReferenceType},
resolve::{
find_context_file,
origin::{PlainResolveOrigin, ResolveOrigin, ResolveOriginExt},
parse::Request,
pattern::Pattern,
resolve, FindContextFileResult, ModulePart,
},
source::Source,
source_map::{
utils::resolve_source_map_sources, GenerateSourceMap, OptionStringifiedSourceMap,
},
};
use turbopack_resolve::{
ecmascript::{apply_cjs_specific_options, cjs_resolve_source},
typescript::tsconfig,
};
use turbopack_swc_utils::emitter::IssueEmitter;
use unreachable::Unreachable;
use worker::WorkerAssetReference;
use self::{
amd::{
AmdDefineAssetReference, AmdDefineDependencyElement, AmdDefineFactoryType,
AmdDefineWithDependenciesCodeGen,
},
cjs::CjsAssetReference,
esm::{
export::EsmExport, EsmAssetReference, EsmAsyncAssetReference, EsmExports, EsmModuleItem,
ImportMetaBinding, ImportMetaRef, UrlAssetReference,
},
node::DirAssetReference,
raw::FileSourceReference,
typescript::{TsConfigReference, TsReferencePathAssetReference, TsReferenceTypeAssetReference},
};
use super::{
analyzer::{
builtin::replace_builtin,
graph::{create_graph, Effect},
linker::link,
well_known::replace_well_known,
ConstantValue as JsConstantValue, JsValue, ObjectPart, WellKnownFunctionKind,
WellKnownObjectKind,
},
errors,
parse::ParseResult,
special_cases::special_cases,
utils::js_value_to_pattern,
webpack::{
parse::{webpack_runtime, WebpackRuntime},
WebpackChunkAssetReference, WebpackEntryAssetReference, WebpackRuntimeAssetReference,
},
EcmascriptModuleAssetType, ModuleTypeResult,
};
pub use crate::references::esm::export::{follow_reexports, FollowExportsResult};
use crate::{
analyzer::{
builtin::early_replace_builtin,
graph::{ConditionalKind, EffectArg, EvalContext, VarGraph},
imports::{ImportAnnotations, ImportAttributes, ImportedSymbol, Reexport},
parse_require_context,
top_level_await::has_top_level_await,
ConstantNumber, ConstantString, JsValueUrlKind, RequireContextValue,
},
chunk::EcmascriptExports,
code_gen::{CodeGen, CodeGens, IntoCodeGenReference},
magic_identifier,
parse::parse,
references::{
async_module::{AsyncModule, OptionAsyncModule},
cjs::{CjsRequireAssetReference, CjsRequireCacheAccess, CjsRequireResolveAssetReference},
dynamic_expression::DynamicExpression,
esm::{
base::EsmAssetReferences, module_id::EsmModuleIdAssetReference, EsmBinding,
UrlRewriteBehavior,
},
ident::IdentReplacement,
member::MemberReplacement,
node::PackageJsonReference,
require_context::{RequireContextAssetReference, RequireContextMap},
type_issue::SpecifiedModuleTypeIssue,
},
runtime_functions::{
TUBROPACK_RUNTIME_FUNCTION_SHORTCUTS, TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_EXPORT_VALUE,
TURBOPACK_REQUIRE_REAL, TURBOPACK_REQUIRE_STUB,
},
tree_shake::{find_turbopack_part_id_in_asserts, part_of_module, split},
utils::{module_value_to_well_known_object, AstPathRange},
EcmascriptInputTransforms, EcmascriptModuleAsset, EcmascriptParsable, SpecifiedModuleType,
TreeShakingMode,
};
#[turbo_tasks::value(shared)]
pub struct AnalyzeEcmascriptModuleResult {
references: Vec<ResolvedVc<Box<dyn ModuleReference>>>,
pub esm_references: ResolvedVc<EsmAssetReferences>,
pub esm_local_references: ResolvedVc<EsmAssetReferences>,
pub esm_reexport_references: ResolvedVc<EsmAssetReferences>,
pub esm_evaluation_references: ResolvedVc<EsmAssetReferences>,
pub code_generation: ResolvedVc<CodeGens>,
pub exports: ResolvedVc<EcmascriptExports>,
pub async_module: ResolvedVc<OptionAsyncModule>,
pub has_side_effect_free_directive: bool,
/// `true` when the analysis was successful.
pub successful: bool,
pub source_map: ResolvedVc<OptionStringifiedSourceMap>,
}
#[turbo_tasks::value_impl]
impl AnalyzeEcmascriptModuleResult {
#[turbo_tasks::function]
pub async fn references(&self) -> Result<Vc<ModuleReferences>> {
Ok(Vc::cell(
self.esm_references
.await?
.iter()
.map(|r| ResolvedVc::upcast(*r))
.chain(self.references.iter().copied())
.collect(),
))
}
#[turbo_tasks::function]
pub async fn local_references(&self) -> Result<Vc<ModuleReferences>> {
Ok(Vc::cell(
self.esm_local_references
.await?
.iter()
.map(|r| ResolvedVc::upcast(*r))
.chain(self.references.iter().copied())
.collect(),
))
}
}
/// A temporary analysis result builder to pass around, to be turned into an
/// `Vc<AnalyzeEcmascriptModuleResult>` eventually.
pub struct AnalyzeEcmascriptModuleResultBuilder {
references: FxIndexSet<ResolvedVc<Box<dyn ModuleReference>>>,
esm_references: FxHashSet<usize>,
esm_local_references: FxHashSet<usize>,
esm_reexport_references: FxHashSet<usize>,
esm_evaluation_references: FxHashSet<usize>,
esm_references_free_var: FxIndexMap<RcStr, ResolvedVc<EsmAssetReference>>,
// Ad-hoc created import references that are resolved `import * as x from ...; x.foo` accesses
// This caches repeated access because EsmAssetReference::new is not a turbo task function.
esm_references_rewritten: FxHashMap<usize, FxIndexMap<RcStr, ResolvedVc<EsmAssetReference>>>,
code_gens: Vec<CodeGen>,
exports: EcmascriptExports,
async_module: ResolvedVc<OptionAsyncModule>,
successful: bool,
source_map: Option<ResolvedVc<OptionStringifiedSourceMap>>,
has_side_effect_free_directive: bool,
}
impl AnalyzeEcmascriptModuleResultBuilder {
pub fn new() -> Self {
Self {
references: Default::default(),
esm_references: Default::default(),
esm_local_references: Default::default(),
esm_reexport_references: Default::default(),
esm_evaluation_references: Default::default(),
esm_references_rewritten: Default::default(),
esm_references_free_var: Default::default(),
code_gens: Default::default(),
exports: EcmascriptExports::None,
async_module: ResolvedVc::cell(None),
successful: false,
source_map: None,
has_side_effect_free_directive: false,
}
}
/// Adds an asset reference to the analysis result.
pub fn add_reference(&mut self, reference: ResolvedVc<impl Upcast<Box<dyn ModuleReference>>>) {
let r = ResolvedVc::upcast(reference);
self.references.insert(r);
}
/// Adds an asset reference with codegen to the analysis result.
pub fn add_reference_code_gen<R: IntoCodeGenReference>(&mut self, reference: R, path: AstPath) {
let (reference, code_gen) = reference.into_code_gen_reference(path);
self.add_reference(reference);
self.add_code_gen(code_gen);
}
/// Adds an ESM asset reference to the analysis result.
pub fn add_esm_reference(&mut self, idx: usize) {
self.esm_references.insert(idx);
self.esm_local_references.insert(idx);
}
/// Adds an reexport ESM reference to the analysis result.
/// If you're unsure about which function to use, use `add_reference()`
pub fn add_esm_reexport_reference(&mut self, idx: usize) {
self.esm_references.insert(idx);
self.esm_reexport_references.insert(idx);
}
/// Adds an evaluation ESM reference to the analysis result.
/// If you're unsure about which function to use, use `add_reference()`
pub fn add_esm_evaluation_reference(&mut self, idx: usize) {
self.esm_references.insert(idx);
self.esm_evaluation_references.insert(idx);
}
/// Adds a codegen to the analysis result.
pub fn add_code_gen<C>(&mut self, code_gen: C)
where
C: Into<CodeGen>,
{
self.code_gens.push(code_gen.into())
}
/// Sets the analysis result ES export.
pub fn set_source_map(&mut self, source_map: ResolvedVc<OptionStringifiedSourceMap>) {
self.source_map = Some(source_map);
}
/// Sets the analysis result ES export.
pub fn set_exports(&mut self, exports: EcmascriptExports) {
self.exports = exports;
}
/// Sets the analysis result ES export.
pub fn set_async_module(&mut self, async_module: ResolvedVc<AsyncModule>) {
self.async_module = ResolvedVc::cell(Some(async_module));
}
/// Set whether this module is side-efffect free according to a user-provided directive.
pub fn set_has_side_effect_free_directive(&mut self, value: bool) {
self.has_side_effect_free_directive = value;
}
/// Sets whether the analysis was successful.
pub fn set_successful(&mut self, successful: bool) {
self.successful = successful;
}
pub fn add_esm_reference_namespace_resolved(
&mut self,
esm_reference_idx: usize,
export: RcStr,
on_insert: impl FnOnce() -> ResolvedVc<EsmAssetReference>,
) -> ResolvedVc<EsmAssetReference> {
*self
.esm_references_rewritten
.entry(esm_reference_idx)
.or_default()
.entry(export)
.or_insert_with(on_insert)
}
pub async fn add_esm_reference_free_var(
&mut self,
request: RcStr,
on_insert: impl AsyncFnOnce() -> Result<ResolvedVc<EsmAssetReference>>,
) -> Result<ResolvedVc<EsmAssetReference>> {
Ok(match self.esm_references_free_var.entry(request) {
Entry::Occupied(e) => *e.get(),
Entry::Vacant(e) => *e.insert(on_insert().await?),
})
}
/// Builds the final analysis result. Resolves internal Vcs.
pub async fn build(
mut self,
import_references: Vec<ResolvedVc<EsmAssetReference>>,
track_reexport_references: bool,
) -> Result<Vc<AnalyzeEcmascriptModuleResult>> {
// esm_references_rewritten (and esm_references_free_var) needs to be spliced in at the
// correct index into esm_references and esm_local_references
let mut esm_references = Vec::with_capacity(
self.esm_references.len()
+ self.esm_references_free_var.len()
+ self.esm_references_rewritten.len(),
);
esm_references.extend(self.esm_references_free_var.values());
let mut esm_local_references = track_reexport_references.then(|| {
let mut esm_local_references = Vec::with_capacity(
self.esm_local_references.len()
+ self.esm_references_free_var.len()
+ self.esm_references_rewritten.len(),
);
esm_local_references.extend(self.esm_references_free_var.values());
esm_local_references
});
let mut esm_reexport_references = track_reexport_references
.then(|| Vec::with_capacity(self.esm_reexport_references.len()));
let mut esm_evaluation_references = track_reexport_references
.then(|| Vec::with_capacity(self.esm_evaluation_references.len()));
for (i, reference) in import_references.iter().enumerate() {
if self.esm_references.contains(&i) {
esm_references.push(*reference);
}
esm_references.extend(
self.esm_references_rewritten
.get(&i)
.iter()
.flat_map(|m| m.values().copied()),
);
if let Some(esm_local_references) = &mut esm_local_references {
if self.esm_local_references.contains(&i) {
esm_local_references.push(*reference);
}
esm_local_references.extend(
self.esm_references_rewritten
.get(&i)
.iter()
.flat_map(|m| m.values().copied()),
);
}
if let Some(esm_evaluation_references) = &mut esm_evaluation_references {
if self.esm_evaluation_references.contains(&i) {
esm_evaluation_references.push(*reference);
}
}
if let Some(esm_reexport_references) = &mut esm_reexport_references {
if self.esm_reexport_references.contains(&i) {
esm_reexport_references.push(*reference);
}
}
}
let references: Vec<_> = self.references.into_iter().collect();
let source_map = if let Some(source_map) = self.source_map {
source_map
} else {
OptionStringifiedSourceMap::none().to_resolved().await?
};
self.code_gens.shrink_to_fit();
Ok(AnalyzeEcmascriptModuleResult::cell(
AnalyzeEcmascriptModuleResult {
references,
esm_references: ResolvedVc::cell(esm_references),
esm_local_references: ResolvedVc::cell(esm_local_references.unwrap_or_default()),
esm_reexport_references: ResolvedVc::cell(
esm_reexport_references.unwrap_or_default(),
),
esm_evaluation_references: ResolvedVc::cell(
esm_evaluation_references.unwrap_or_default(),
),
code_generation: ResolvedVc::cell(self.code_gens),
exports: self.exports.resolved_cell(),
async_module: self.async_module,
has_side_effect_free_directive: self.has_side_effect_free_directive,
successful: self.successful,
source_map,
},
))
}
}
impl Default for AnalyzeEcmascriptModuleResultBuilder {
fn default() -> Self {
Self::new()
}
}
struct AnalysisState<'a> {
handler: &'a Handler,
source: ResolvedVc<Box<dyn Source>>,
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
compile_time_info: ResolvedVc<CompileTimeInfo>,
var_graph: &'a VarGraph,
/// This is the current state of known values of function
/// arguments.
fun_args_values: Mutex<FxHashMap<u32, Vec<JsValue>>>,
var_cache: Mutex<FxHashMap<Id, JsValue>>,
// There can be many references to import.meta, but only the first should hoist
// the object allocation.
first_import_meta: bool,
tree_shaking_mode: Option<TreeShakingMode>,
import_externals: bool,
ignore_dynamic_requests: bool,
url_rewrite_behavior: Option<UrlRewriteBehavior>,
free_var_references: ReadRef<FreeVarReferencesIndividual>,
}
impl AnalysisState<'_> {
/// Links a value to the graph, returning the linked value.
async fn link_value(&self, value: JsValue, attributes: &ImportAttributes) -> Result<JsValue> {
Ok(link(
self.var_graph,
value,
&early_value_visitor,
&|value| {
value_visitor(
*self.origin,
value,
*self.compile_time_info,
&self.free_var_references,
self.var_graph,
attributes,
)
},
&self.fun_args_values,
&self.var_cache,
)
.await?
.0)
}
}
fn set_handler_and_globals<F, R>(handler: &Handler, globals: &Arc<Globals>, f: F) -> R
where
F: FnOnce() -> R,
{
HANDLER.set(handler, || GLOBALS.set(globals, f))
}
/// Analyse a provided [EcmascriptModuleAsset] and return a [AnalyzeEcmascriptModuleResult].
#[turbo_tasks::function]
pub(crate) async fn analyse_ecmascript_module(
module: ResolvedVc<EcmascriptModuleAsset>,
part: Option<ModulePart>,
) -> Result<Vc<AnalyzeEcmascriptModuleResult>> {
let span = {
let module = module.ident().to_string().await?.to_string();
tracing::info_span!("analyse ecmascript module", module = module)
};
let result = analyse_ecmascript_module_internal(module, part)
.instrument(span)
.await;
match result {
Ok(result) => Ok(result),
Err(err) => Err(err.context(format!(
"failed to analyse ecmascript module '{}'",
module.ident().to_string().await?
))),
}
}
pub(crate) async fn analyse_ecmascript_module_internal(
module: ResolvedVc<EcmascriptModuleAsset>,
part: Option<ModulePart>,
) -> Result<Vc<AnalyzeEcmascriptModuleResult>> {
let raw_module = module.await?;
let source = raw_module.source;
let ty = Value::new(raw_module.ty);
let transforms = raw_module.transforms;
let options = raw_module.options;
let options = options.await?;
let import_externals = options.import_externals;
let origin = ResolvedVc::upcast::<Box<dyn ResolveOrigin>>(module);
let mut analysis = AnalyzeEcmascriptModuleResultBuilder::new();
let path = origin.origin_path();
// Is this a typescript file that requires analzying type references?
let analyze_types = match &*ty {
EcmascriptModuleAssetType::Typescript { analyze_types, .. } => *analyze_types,
EcmascriptModuleAssetType::TypescriptDeclaration => true,
EcmascriptModuleAssetType::Ecmascript => false,
};
let parsed = if let Some(part) = part {
let parsed = parse(*source, ty, *transforms);
let split_data = split(source.ident(), *source, parsed);
part_of_module(split_data, part.clone())
} else {
module.failsafe_parse()
};
let ModuleTypeResult {
module_type: specified_type,
referenced_package_json,
} = *module.determine_module_type().await?;
if let Some(package_json) = referenced_package_json {
let span = tracing::info_span!("package.json reference");
async {
analysis.add_reference(
PackageJsonReference::new(*package_json)
.to_resolved()
.await?,
);
anyhow::Ok(())
}
.instrument(span)
.await?;
}
if analyze_types {
let span = tracing::info_span!("tsconfig reference");
async {
match &*find_context_file(path.parent(), tsconfig()).await? {
FindContextFileResult::Found(tsconfig, _) => {
analysis.add_reference(
TsConfigReference::new(*origin, **tsconfig)
.to_resolved()
.await?,
);
}
FindContextFileResult::NotFound(_) => {}
};
anyhow::Ok(())
}
.instrument(span)
.await?;
}
special_cases(&path.await?.path, &mut analysis);
let parsed = parsed.await?;
let ParseResult::Ok {
program,
globals,
eval_context,
comments,
source_map,
..
} = &*parsed
else {
return analysis.build(Default::default(), false).await;
};
let has_side_effect_free_directive = match program {
Program::Module(module) => Either::Left(
module
.body
.iter()
.take_while(|i| match i {
ModuleItem::Stmt(stmt) => stmt.directive_continue(),
ModuleItem::ModuleDecl(_) => false,
})
.filter_map(|i| i.as_stmt()),
),
Program::Script(script) => Either::Right(
script
.body
.iter()
.take_while(|stmt| stmt.directive_continue()),
),
}
.any(|f| match f {
Stmt::Expr(ExprStmt { expr, .. }) => match &**expr {
Expr::Lit(Lit::Str(Str { value, .. })) => value == "use turbopack no side effects",
_ => false,
},
_ => false,
});
analysis.set_has_side_effect_free_directive(has_side_effect_free_directive);
let compile_time_info = compile_time_info_for_module_type(
*raw_module.compile_time_info,
eval_context.is_esm(specified_type),
)
.to_resolved()
.await?;
let pos = program.span().lo;
if analyze_types {
let span = tracing::info_span!("type references");
async {
if let Some(comments) = comments.get_leading(pos) {
for comment in comments.iter() {
if let CommentKind::Line = comment.kind {
lazy_static! {
static ref REFERENCE_PATH: Regex =
Regex::new(r#"^/\s*<reference\s*path\s*=\s*["'](.+)["']\s*/>\s*$"#)
.unwrap();
static ref REFERENCE_TYPES: Regex = Regex::new(
r#"^/\s*<reference\s*types\s*=\s*["'](.+)["']\s*/>\s*$"#
)
.unwrap();
}
let text = &comment.text;
if let Some(m) = REFERENCE_PATH.captures(text) {
let path = &m[1];
analysis.add_reference(
TsReferencePathAssetReference::new(*origin, path.into())
.to_resolved()
.await?,
);
} else if let Some(m) = REFERENCE_TYPES.captures(text) {
let types = &m[1];
analysis.add_reference(
TsReferenceTypeAssetReference::new(*origin, types.into())
.to_resolved()
.await?,
);
}
}
}
}
anyhow::Ok(())
}
.instrument(span)
.await?;
}
if options.extract_source_map {
let span = tracing::info_span!("source map reference");
async {
// Only use the last sourceMappingURL comment by spec
let mut paths_by_pos = Vec::new();
for (pos, comments) in comments.trailing.iter() {
for comment in comments.iter().rev() {
lazy_static! {
static ref SOURCE_MAP_FILE_REFERENCE: Regex =
Regex::new(r"# sourceMappingURL=(.*)$").unwrap();
}
if let Some(m) = SOURCE_MAP_FILE_REFERENCE.captures(&comment.text) {
let path = m.get(1).unwrap().as_str();
paths_by_pos.push((pos, path));
break;
}
}
}
let mut source_map_from_comment = false;
if let Some((_, path)) = paths_by_pos.into_iter().max_by_key(|&(pos, _)| pos) {
lazy_static! {
static ref JSON_DATA_URL_BASE64: Regex =
Regex::new(r"^data:application\/json;(?:charset=utf-8;)?base64").unwrap();
}
let origin_path = origin.origin_path();
if path.ends_with(".map") {
let source_map_origin = origin_path.parent().join(path.into());
let reference = SourceMapReference::new(origin_path, source_map_origin)
.to_resolved()
.await?;
analysis.add_reference(reference);
let source_map = reference.generate_source_map();
analysis.set_source_map(source_map.to_resolved().await?);
source_map_from_comment = true;
} else if JSON_DATA_URL_BASE64.is_match(path) {
let source_map = maybe_decode_data_url(path.into());
let source_map =
resolve_source_map_sources(source_map.as_ref(), origin_path).await?;
analysis.set_source_map(ResolvedVc::cell(source_map));
source_map_from_comment = true;
}
}
if !source_map_from_comment {
if let Some(generate_source_map) =
ResolvedVc::try_sidecast::<Box<dyn GenerateSourceMap>>(source)
{
analysis.set_source_map(
generate_source_map
.generate_source_map()
.to_resolved()
.await?,
);
}
}
anyhow::Ok(())
}
.instrument(span)
.await?;
}
let (emitter, collector) = IssueEmitter::new(source, source_map.clone(), None);
let handler = Handler::with_emitter(true, false, Box::new(emitter));
let mut var_graph = {
let _span = tracing::info_span!("analyze variable values");
set_handler_and_globals(&handler, globals, || create_graph(program, eval_context))
};
let span = tracing::info_span!("esm import references");
let import_references = async {
let mut import_references = Vec::with_capacity(eval_context.imports.references().len());
for (i, r) in eval_context.imports.references().enumerate() {
let mut should_add_evaluation = false;
let reference = EsmAssetReference::new(
origin,
Request::parse(Value::new(RcStr::from(&*r.module_path).into()))
.to_resolved()
.await?,
r.issue_source
.clone()
.unwrap_or_else(|| IssueSource::from_source_only(source)),
Value::new(r.annotations.clone()),
match options.tree_shaking_mode {
Some(TreeShakingMode::ModuleFragments) => match &r.imported_symbol {
ImportedSymbol::ModuleEvaluation => {
should_add_evaluation = true;
Some(ModulePart::evaluation())
}
ImportedSymbol::Symbol(name) => Some(ModulePart::export((&**name).into())),
ImportedSymbol::PartEvaluation(part_id) => {
should_add_evaluation = true;
Some(ModulePart::internal_evaluation(*part_id))
}
ImportedSymbol::Part(part_id) => Some(ModulePart::internal(*part_id)),
ImportedSymbol::Exports => Some(ModulePart::exports()),
},
Some(TreeShakingMode::ReexportsOnly) => match &r.imported_symbol {
ImportedSymbol::ModuleEvaluation => {
should_add_evaluation = true;
Some(ModulePart::evaluation())
}
ImportedSymbol::Symbol(name) => Some(ModulePart::export((&**name).into())),
ImportedSymbol::PartEvaluation(_) | ImportedSymbol::Part(_) => {
bail!(
"Internal imports doesn't exist in reexports only mode when \
importing {:?} from {}",
r.imported_symbol,
r.module_path
);
}
ImportedSymbol::Exports => None,
},
None => {
should_add_evaluation = true;
None
}
},
import_externals,
)
.resolved_cell();
import_references.push(reference);
if should_add_evaluation {
analysis.add_esm_evaluation_reference(i);
}
}
anyhow::Ok(import_references)
}
.instrument(span)
.await?;
let span = tracing::info_span!("exports");
let (webpack_runtime, webpack_entry, webpack_chunks) = async {
let (webpack_runtime, webpack_entry, webpack_chunks, mut esm_exports) =
set_handler_and_globals(&handler, globals, || {
// TODO migrate to effects
let mut visitor =
ModuleReferencesVisitor::new(eval_context, &import_references, &mut analysis);
// ModuleReferencesVisitor has already called analysis.add_esm_reexport_reference
// for any references in esm_exports
program.visit_with_ast_path(&mut visitor, &mut Default::default());
(
visitor.webpack_runtime,
visitor.webpack_entry,
visitor.webpack_chunks,
visitor.esm_exports,
)
});
let mut esm_star_exports: Vec<ResolvedVc<Box<dyn ModuleReference>>> = vec![];
for (i, reexport) in eval_context.imports.reexports() {
let reference = import_references[i];
match reexport {
Reexport::Star => {
esm_star_exports.push(ResolvedVc::upcast(reference));
analysis.add_esm_reexport_reference(i);
}
Reexport::Namespace { exported: n } => {
esm_exports.insert(
n.as_str().into(),
EsmExport::ImportedNamespace(ResolvedVc::upcast(reference)),
);
analysis.add_esm_reexport_reference(i);
}
Reexport::Named { imported, exported } => {
esm_exports.insert(
exported.as_str().into(),
EsmExport::ImportedBinding(
ResolvedVc::upcast(reference),
imported.to_string().into(),
false,
),
);
analysis.add_esm_reexport_reference(i);
}
}
}
let exports = if !esm_exports.is_empty() || !esm_star_exports.is_empty() {
if specified_type == SpecifiedModuleType::CommonJs {
SpecifiedModuleTypeIssue {
path: source.ident().path().to_resolved().await?,
specified_type,
}
.resolved_cell()
.emit();
}
let esm_exports = EsmExports {
exports: esm_exports,
star_exports: esm_star_exports,
}
.cell();
EcmascriptExports::EsmExports(esm_exports.to_resolved().await?)
} else if specified_type == SpecifiedModuleType::EcmaScript {
match detect_dynamic_export(program) {
DetectedDynamicExportType::CommonJs => {
SpecifiedModuleTypeIssue {
path: source.ident().path().to_resolved().await?,
specified_type,
}
.resolved_cell()
.emit();
EcmascriptExports::EsmExports(
EsmExports {
exports: Default::default(),
star_exports: Default::default(),
}
.resolved_cell(),
)
}
DetectedDynamicExportType::Namespace => EcmascriptExports::DynamicNamespace,
DetectedDynamicExportType::Value => EcmascriptExports::Value,
DetectedDynamicExportType::UsingModuleDeclarations
| DetectedDynamicExportType::None => EcmascriptExports::EsmExports(
EsmExports {
exports: Default::default(),
star_exports: Default::default(),
}
.resolved_cell(),
),
}
} else {
match detect_dynamic_export(program) {
DetectedDynamicExportType::CommonJs => EcmascriptExports::CommonJs,
DetectedDynamicExportType::Namespace => EcmascriptExports::DynamicNamespace,
DetectedDynamicExportType::Value => EcmascriptExports::Value,
DetectedDynamicExportType::UsingModuleDeclarations => {
EcmascriptExports::EsmExports(
EsmExports {
exports: Default::default(),
star_exports: Default::default(),
}
.resolved_cell(),
)
}
DetectedDynamicExportType::None => EcmascriptExports::EmptyCommonJs,
}
};
analysis.set_exports(exports);
anyhow::Ok((webpack_runtime, webpack_entry, webpack_chunks))
}
.instrument(span)
.await?;
let mut ignore_effect_span = None;
// Check if it was a webpack entry
if let Some((request, webpack_runtime_span)) = webpack_runtime {
let span = tracing::info_span!("webpack runtime reference");
async {
let request = Request::parse(Value::new(request.into()))
.to_resolved()
.await?;
let runtime = resolve_as_webpack_runtime(*origin, *request, *transforms)
.to_resolved()
.await?;
if let WebpackRuntime::Webpack5 { .. } = &*runtime.await? {
ignore_effect_span = Some(webpack_runtime_span);
analysis.add_reference(
WebpackRuntimeAssetReference {
origin,
request,
runtime,
transforms,
}
.resolved_cell(),
);
if webpack_entry {
analysis.add_reference(
WebpackEntryAssetReference {
source,
runtime,
transforms,
}
.resolved_cell(),
);
}
for chunk in webpack_chunks {
analysis.add_reference(
WebpackChunkAssetReference {
chunk_id: chunk,
runtime,
transforms,
}
.resolved_cell(),
);
}
}
anyhow::Ok(())
}
.instrument(span)
.await?;
}
let span = tracing::info_span!("async module handling");
async {
let top_level_await_span =
set_handler_and_globals(&handler, globals, || has_top_level_await(program));
let has_top_level_await = top_level_await_span.is_some();
if eval_context.is_esm(specified_type) {
let async_module = AsyncModule {
has_top_level_await,
import_externals,
}
.resolved_cell();
analysis.set_async_module(async_module);
} else if let Some(span) = top_level_await_span {
AnalyzeIssue::new(
IssueSeverity::Error,
source.ident(),
Vc::cell("unexpected top level await".into()),
StyledString::Text("top level await is only supported in ESM modules.".into())
.cell(),
None,
Some(issue_source(source, span)),
)
.to_resolved()
.await?
.emit();
}