-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
mod.rs
1766 lines (1539 loc) · 54.3 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
use std::{
collections::{HashMap, HashSet},
env,
path::{Path, PathBuf},
sync::Arc,
usize,
};
use anyhow::{bail, Context, Error};
use dashmap::DashMap;
use either::Either;
use indexmap::IndexMap;
use once_cell::sync::Lazy;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use swc_atoms::JsWord;
use swc_cached::regex::CachedRegex;
#[allow(unused)]
use swc_common::plugin::metadata::TransformPluginMetadataContext;
use swc_common::{
chain,
collections::{AHashMap, AHashSet, ARandomState},
comments::{Comments, SingleThreadedComments},
errors::Handler,
FileName, Mark, SourceMap, SyntaxContext,
};
pub use swc_compiler_base::{IsModule, SourceMapsConfig};
use swc_config::{
config_types::{BoolConfig, BoolOr, BoolOrDataConfig, MergingOption},
merge::Merge,
};
use swc_ecma_ast::{EsVersion, Expr, Program};
use swc_ecma_ext_transforms::jest;
use swc_ecma_lints::{
config::LintConfig,
rules::{lint_to_fold, LintParams},
};
use swc_ecma_loader::resolvers::{
lru::CachingResolver, node::NodeModulesResolver, tsc::TsConfigResolver,
};
pub use swc_ecma_minifier::js::*;
use swc_ecma_minifier::option::terser::TerserTopLevelOptions;
#[allow(deprecated)]
pub use swc_ecma_parser::JscTarget;
use swc_ecma_parser::{parse_file_as_expr, Syntax, TsConfig};
use swc_ecma_transforms::{
feature::FeatureFlag,
hygiene, modules,
modules::{path::NodeImportResolver, rewriter::import_rewriter, EsModuleConfig},
optimization::{const_modules, json_parse, simplifier},
pass::{noop, Optional},
proposals::{
decorators, explicit_resource_management::explicit_resource_management,
export_default_from, import_assertions,
},
react::{self, default_pragma, default_pragma_frag},
resolver,
typescript::{self, TsImportExportAssignConfig},
Assumptions,
};
use swc_ecma_transforms_compat::es2015::regenerator;
use swc_ecma_transforms_optimization::{
inline_globals2,
simplify::{dce::Config as DceConfig, Config as SimplifyConfig},
GlobalExprMap,
};
use swc_ecma_utils::NodeIgnoringSpan;
use swc_ecma_visit::{Fold, VisitMutWith};
pub use crate::plugin::PluginConfig;
use crate::{
builder::PassBuilder, dropped_comments_preserver::dropped_comments_preserver, SwcImportResolver,
};
#[cfg(test)]
mod tests;
#[cfg(feature = "plugin")]
/// A shared instance to plugin's module bytecode cache.
pub static PLUGIN_MODULE_CACHE: Lazy<swc_plugin_runner::cache::PluginModuleCache> =
Lazy::new(Default::default);
/// Create a new cache instance if not initialized. This can be called multiple
/// time, but any subsequent call will be ignored.
///
/// This fn have a side effect to create path to cache if given path is not
/// resolvable if fs_cache_store is enabled. If root is not specified, it'll
/// generate default root for cache location.
///
/// If cache failed to initialize filesystem cache for given location
/// it'll be serve in-memory cache only.
#[cfg(feature = "plugin")]
pub fn init_plugin_module_cache_once(
enable_fs_cache_store: bool,
fs_cache_store_root: &Option<String>,
) {
PLUGIN_MODULE_CACHE.inner.get_or_init(|| {
parking_lot::Mutex::new(swc_plugin_runner::cache::PluginModuleCache::create_inner(
enable_fs_cache_store,
fs_cache_store_root,
))
});
}
#[derive(Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ParseOptions {
#[serde(default)]
pub comments: bool,
#[serde(flatten)]
pub syntax: Syntax,
#[serde(default)]
pub is_module: IsModule,
#[serde(default)]
pub target: EsVersion,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Options {
#[serde(flatten)]
pub config: Config,
#[serde(skip_deserializing, default)]
pub skip_helper_injection: bool,
#[serde(skip_deserializing, default)]
pub disable_hygiene: bool,
#[serde(skip_deserializing, default)]
pub disable_fixer: bool,
#[serde(skip_deserializing, default)]
pub top_level_mark: Option<Mark>,
#[serde(skip_deserializing, default)]
pub unresolved_mark: Option<Mark>,
#[cfg(not(target_arch = "wasm32"))]
#[serde(default = "default_cwd")]
pub cwd: PathBuf,
#[serde(default)]
pub caller: Option<CallerOptions>,
#[serde(default)]
pub filename: String,
#[serde(default)]
pub config_file: Option<ConfigFile>,
#[serde(default)]
pub root: Option<PathBuf>,
#[serde(default)]
pub root_mode: RootMode,
#[serde(default = "default_swcrc")]
pub swcrc: bool,
#[cfg(not(target_arch = "wasm32"))]
#[serde(default)]
pub swcrc_roots: Option<PathBuf>,
#[serde(default = "default_env_name")]
pub env_name: String,
#[serde(default)]
pub source_maps: Option<SourceMapsConfig>,
#[serde(default)]
pub source_file_name: Option<String>,
#[serde(default)]
pub source_root: Option<String>,
#[serde(default)]
pub output_path: Option<PathBuf>,
#[serde(default)]
pub experimental: ExperimentalOptions,
}
#[derive(Debug, Clone, Default, Deserialize, Merge)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ExperimentalOptions {
#[serde(default)]
pub error_format: Option<ErrorFormat>,
}
impl Options {
pub fn codegen_target(&self) -> Option<EsVersion> {
self.config.jsc.target
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum InputSourceMap {
Bool(bool),
Str(String),
}
impl Default for InputSourceMap {
fn default() -> Self {
InputSourceMap::Bool(false)
}
}
impl Options {
/// `parse`: `(syntax, target, is_module)`
///
/// `parse` should use `comments`.
#[allow(clippy::too_many_arguments)]
pub fn build_as_input<'a, P>(
&self,
cm: &Arc<SourceMap>,
base: &FileName,
parse: impl FnOnce(Syntax, EsVersion, IsModule) -> Result<Program, Error>,
output_path: Option<&Path>,
source_file_name: Option<String>,
handler: &Handler,
config: Option<Config>,
comments: Option<&'a SingleThreadedComments>,
custom_before_pass: impl FnOnce(&Program) -> P,
) -> Result<BuiltInput<Box<dyn 'a + Fold>>, Error>
where
P: 'a + swc_ecma_visit::Fold,
{
let mut cfg = self.config.clone();
cfg.merge(config.unwrap_or_default());
if let FileName::Real(base) = base {
cfg.adjust(base);
}
let is_module = cfg.is_module.unwrap_or_default();
let mut source_maps = self.source_maps.clone();
source_maps.merge(cfg.source_maps.clone());
let JscConfig {
assumptions,
transform,
syntax,
external_helpers,
target,
loose,
keep_class_names,
base_url,
paths,
minify: mut js_minify,
experimental,
lints,
preserve_all_comments,
..
} = cfg.jsc;
let loose = loose.into_bool();
let preserve_all_comments = preserve_all_comments.into_bool();
let keep_class_names = keep_class_names.into_bool();
let external_helpers = external_helpers.into_bool();
let mut assumptions = assumptions.unwrap_or_else(|| {
if loose {
Assumptions::all()
} else {
Assumptions::default()
}
});
let unresolved_mark = self.unresolved_mark.unwrap_or_else(Mark::new);
let top_level_mark = self.top_level_mark.unwrap_or_else(Mark::new);
if target.is_some() && cfg.env.is_some() {
bail!("`env` and `jsc.target` cannot be used together");
}
let es_version = target.unwrap_or_default();
let syntax = syntax.unwrap_or_default();
let mut program = parse(syntax, es_version, is_module)?;
let mut transform = transform.into_inner().unwrap_or_default();
// Do a resolver pass before everything.
//
// We do this before creating custom passes, so custom passses can use the
// variable management system based on the syntax contexts.
if syntax.typescript() {
assumptions.set_class_methods |= !transform.use_define_for_class_fields.into_bool();
}
assumptions.set_public_class_fields |= !transform.use_define_for_class_fields.into_bool();
program.visit_mut_with(&mut resolver(
unresolved_mark,
top_level_mark,
syntax.typescript(),
));
if program.is_module() {
js_minify = js_minify.map(|c| {
let compress = c
.compress
.unwrap_as_option(|default| match default {
Some(true) => Some(Default::default()),
_ => None,
})
.map(|mut c| {
if c.toplevel.is_none() {
c.toplevel = Some(TerserTopLevelOptions::Bool(true));
}
if matches!(
cfg.module,
None | Some(ModuleConfig::Es6(..) | ModuleConfig::NodeNext(..))
) {
c.module = true;
}
c
})
.map(BoolOrDataConfig::from_obj)
.unwrap_or_else(|| BoolOrDataConfig::from_bool(false));
let mangle = c
.mangle
.unwrap_as_option(|default| match default {
Some(true) => Some(Default::default()),
_ => None,
})
.map(|mut c| {
if c.top_level.is_none() {
c.top_level = Some(true);
}
c
})
.map(BoolOrDataConfig::from_obj)
.unwrap_or_else(|| BoolOrDataConfig::from_bool(false));
JsMinifyOptions {
compress,
mangle,
..c
}
});
}
if js_minify.is_some() && js_minify.as_ref().unwrap().keep_fnames {
js_minify = js_minify.map(|c| {
let compress = c
.compress
.unwrap_as_option(|default| match default {
Some(true) => Some(Default::default()),
_ => None,
})
.map(|mut c| {
c.keep_fnames = true;
c
})
.map(BoolOrDataConfig::from_obj)
.unwrap_or_else(|| BoolOrDataConfig::from_bool(false));
let mangle = c
.mangle
.unwrap_as_option(|default| match default {
Some(true) => Some(Default::default()),
_ => None,
})
.map(|mut c| {
c.keep_fn_names = true;
c
})
.map(BoolOrDataConfig::from_obj)
.unwrap_or_else(|| BoolOrDataConfig::from_bool(false));
JsMinifyOptions {
compress,
mangle,
..c
}
});
}
if js_minify.is_some() && js_minify.as_ref().unwrap().keep_classnames {
js_minify = js_minify.map(|c| {
let compress = c
.compress
.unwrap_as_option(|default| match default {
Some(true) => Some(Default::default()),
_ => None,
})
.map(|mut c| {
c.keep_classnames = true;
c
})
.map(BoolOrDataConfig::from_obj)
.unwrap_or_else(|| BoolOrDataConfig::from_bool(false));
let mangle = c
.mangle
.unwrap_as_option(|default| match default {
Some(true) => Some(Default::default()),
_ => None,
})
.map(|mut c| {
c.keep_class_names = true;
c
})
.map(BoolOrDataConfig::from_obj)
.unwrap_or_else(|| BoolOrDataConfig::from_bool(false));
JsMinifyOptions {
compress,
mangle,
..c
}
});
}
let regenerator = transform.regenerator.clone();
let preserve_comments = if preserve_all_comments {
BoolOr::Bool(true)
} else {
js_minify
.as_ref()
.map(|v| match v.format.comments.clone().into_inner() {
Some(v) => v,
None => BoolOr::Bool(true),
})
.unwrap_or_else(|| {
BoolOr::Data(if cfg.minify.into_bool() {
JsMinifyCommentOption::PreserveSomeComments
} else {
JsMinifyCommentOption::PreserveAllComments
})
})
};
if syntax.typescript() {
transform.legacy_decorator = true.into();
}
let optimizer = transform.optimizer;
let const_modules = {
let enabled = transform.const_modules.is_some();
let config = transform.const_modules.unwrap_or_default();
let globals = config.globals;
Optional::new(const_modules(cm.clone(), globals), enabled)
};
let json_parse_pass = {
if let Some(ref cfg) = optimizer.as_ref().and_then(|v| v.jsonify) {
Either::Left(json_parse(cfg.min_cost))
} else {
Either::Right(noop())
}
};
let simplifier_pass = {
if let Some(ref opts) = optimizer.as_ref().and_then(|o| o.simplify) {
match opts {
SimplifyOption::Bool(allow_simplify) => {
if *allow_simplify {
Either::Left(simplifier(top_level_mark, Default::default()))
} else {
Either::Right(noop())
}
}
SimplifyOption::Json(cfg) => Either::Left(simplifier(
top_level_mark,
SimplifyConfig {
dce: DceConfig {
preserve_imports_with_side_effects: cfg
.preserve_imports_with_side_effects,
..Default::default()
},
..Default::default()
},
)),
}
} else {
Either::Right(noop())
}
};
let optimization = {
if let Some(opts) = optimizer.and_then(|o| o.globals) {
Either::Left(opts.build(cm, handler))
} else {
Either::Right(noop())
}
};
let unresolved_ctxt = SyntaxContext::empty().apply_mark(unresolved_mark);
let top_level_ctxt = SyntaxContext::empty().apply_mark(top_level_mark);
let pass = chain!(
const_modules,
optimization,
Optional::new(export_default_from(), syntax.export_default_from()),
simplifier_pass,
json_parse_pass
);
let import_export_assign_config = match cfg.module {
Some(ModuleConfig::Es6(..)) => TsImportExportAssignConfig::EsNext,
Some(ModuleConfig::CommonJs(..))
| Some(ModuleConfig::Amd(..))
| Some(ModuleConfig::Umd(..)) => TsImportExportAssignConfig::Preserve,
Some(ModuleConfig::NodeNext(..)) => TsImportExportAssignConfig::NodeNext,
// TODO: should Preserve for SystemJS
_ => TsImportExportAssignConfig::Classic,
};
let verbatim_module_syntax = transform.verbatim_module_syntax.into_bool();
let charset = cfg.jsc.output.charset.or_else(|| {
if js_minify.as_ref()?.format.ascii_only {
Some(OutputCharset::Ascii)
} else {
None
}
});
let preamble = if !cfg.jsc.output.preamble.is_empty() {
cfg.jsc.output.preamble
} else {
js_minify
.as_ref()
.map(|v| v.format.preamble.clone())
.unwrap_or_default()
};
let pass = PassBuilder::new(
cm,
handler,
loose,
assumptions,
top_level_mark,
unresolved_mark,
pass,
)
.target(es_version)
.skip_helper_injection(self.skip_helper_injection)
.minify(js_minify)
.hygiene(if self.disable_hygiene {
None
} else {
Some(hygiene::Config {
keep_class_names,
..Default::default()
})
})
.fixer(!self.disable_fixer)
.preset_env(cfg.env)
.regenerator(regenerator)
.finalize(
base_url,
paths.into_iter().collect(),
base,
syntax,
cfg.module,
comments.map(|v| v as _),
);
let keep_import_attributes = experimental.keep_import_attributes.into_bool();
#[cfg(feature = "plugin")]
let plugin_transforms = {
let transform_filename = match base {
FileName::Real(path) => path.as_os_str().to_str().map(String::from),
FileName::Custom(filename) => Some(filename.to_owned()),
_ => None,
};
let transform_metadata_context = Arc::new(TransformPluginMetadataContext::new(
transform_filename,
self.env_name.to_owned(),
None,
));
// Embedded runtime plugin target, based on assumption we have
// 1. filesystem access for the cache
// 2. embedded runtime can compiles & execute wasm
#[cfg(all(feature = "plugin", not(target_arch = "wasm32")))]
{
use swc_ecma_loader::resolve::Resolve;
let plugin_resolver = CachingResolver::new(
40,
NodeModulesResolver::new(
swc_ecma_loader::TargetEnv::Node,
Default::default(),
true,
),
);
if let Some(plugins) = &experimental.plugins {
// Currently swc enables filesystemcache by default on Embedded runtime plugin
// target.
init_plugin_module_cache_once(true, &experimental.cache_root);
let mut inner_cache = PLUGIN_MODULE_CACHE
.inner
.get()
.expect("Cache should be available")
.lock();
// Populate cache to the plugin modules if not loaded
for plugin_config in plugins.iter() {
let plugin_name = &plugin_config.0;
if !inner_cache.contains(&plugin_name) {
let resolved_path = plugin_resolver.resolve(
&FileName::Real(PathBuf::from(&plugin_name)),
&plugin_name,
)?;
let path = if let FileName::Real(value) = resolved_path {
value
} else {
anyhow::bail!("Failed to resolve plugin path: {:?}", resolved_path);
};
inner_cache.store_bytes_from_path(&path, &plugin_name)?;
tracing::debug!("Initialized WASM plugin {plugin_name}");
}
}
}
crate::plugin::plugins(
experimental.plugins,
transform_metadata_context,
comments.cloned(),
cm.clone(),
unresolved_mark,
)
}
// Native runtime plugin target, based on assumption we have
// 1. no filesystem access, loading binary / cache management should be
// performed externally
// 2. native runtime compiles & execute wasm (i.e v8 on node, chrome)
#[cfg(all(feature = "plugin", target_arch = "wasm32"))]
{
handler.warn(
"Currently @swc/wasm does not support plugins, plugin transform will be \
skipped. Refer https://github.com/swc-project/swc/issues/3934 for the details.",
);
noop()
}
};
#[cfg(not(feature = "plugin"))]
let plugin_transforms = {
if experimental.plugins.is_some() {
handler.warn(
"Plugin is not supported with current @swc/core. Plugin transform will be \
skipped.",
);
}
noop()
};
let pass: Box<dyn Fold> = if experimental
.disable_builtin_transforms_for_internal_testing
.into_bool()
{
Box::new(plugin_transforms)
} else {
Box::new(chain!(
lint_to_fold(swc_ecma_lints::rules::all(LintParams {
program: &program,
lint_config: &lints,
top_level_ctxt,
unresolved_ctxt,
es_version,
source_map: cm.clone(),
})),
// Decorators may use type information
Optional::new(
match transform.decorator_version.unwrap_or_default() {
DecoratorVersion::V202112 => {
Either::Left(decorators(decorators::Config {
legacy: transform.legacy_decorator.into_bool(),
emit_metadata: transform.decorator_metadata.into_bool(),
use_define_for_class_fields: !assumptions.set_public_class_fields,
}))
}
DecoratorVersion::V202203 => {
Either::Right(
swc_ecma_transforms::proposals::decorator_2022_03::decorator_2022_03(),
)
}
},
syntax.decorators()
),
Optional::new(
explicit_resource_management(),
syntax.explicit_resource_management()
),
// The transform strips import assertions, so it's only enabled if
// keep_import_assertions is false.
Optional::new(import_assertions(), !keep_import_attributes),
Optional::new(
typescript::tsx::<Option<&dyn Comments>>(
cm.clone(),
typescript::Config {
import_export_assign_config,
verbatim_module_syntax,
..Default::default()
},
typescript::TsxConfig {
pragma: Some(
transform
.react
.pragma
.clone()
.unwrap_or_else(default_pragma)
),
pragma_frag: Some(
transform
.react
.pragma_frag
.clone()
.unwrap_or_else(default_pragma_frag)
),
},
comments.map(|v| v as _),
top_level_mark
),
syntax.typescript()
),
plugin_transforms,
custom_before_pass(&program),
// handle jsx
Optional::new(
react::react::<&dyn Comments>(
cm.clone(),
comments.map(|v| v as _),
transform.react,
top_level_mark,
unresolved_mark
),
syntax.jsx()
),
pass,
Optional::new(jest::jest(), transform.hidden.jest.into_bool()),
Optional::new(
dropped_comments_preserver(comments.cloned()),
preserve_all_comments
),
))
};
Ok(BuiltInput {
program,
minify: cfg.minify.into_bool(),
pass,
external_helpers,
syntax,
target: es_version,
is_module,
source_maps: source_maps.unwrap_or(SourceMapsConfig::Bool(false)),
inline_sources_content: cfg.inline_sources_content.into_bool(),
input_source_map: cfg.input_source_map.clone().unwrap_or_default(),
output_path: output_path.map(|v| v.to_path_buf()),
source_file_name,
comments: comments.cloned(),
preserve_comments,
emit_source_map_columns: cfg.emit_source_map_columns.into_bool(),
output: JscOutputConfig { charset, preamble },
emit_assert_for_import_attributes: experimental
.emit_assert_for_import_attributes
.into_bool(),
})
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum RootMode {
#[serde(rename = "root")]
Root,
#[serde(rename = "upward")]
Upward,
#[serde(rename = "upward-optional")]
UpwardOptional,
}
impl Default for RootMode {
fn default() -> Self {
RootMode::Root
}
}
const fn default_swcrc() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ConfigFile {
Bool(bool),
Str(String),
}
impl Default for ConfigFile {
fn default() -> Self {
ConfigFile::Bool(true)
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CallerOptions {
pub name: String,
}
#[cfg(not(target_arch = "wasm32"))]
fn default_cwd() -> PathBuf {
::std::env::current_dir().unwrap()
}
/// `.swcrc` file
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged, rename = "swcrc")]
#[allow(clippy::large_enum_variant)]
pub enum Rc {
Single(Config),
Multi(Vec<Config>),
}
impl Default for Rc {
fn default() -> Self {
Rc::Multi(vec![
Config {
env: None,
test: None,
exclude: Some(FileMatcher::Regex("\\.tsx?$".into())),
jsc: JscConfig {
syntax: Some(Default::default()),
..Default::default()
},
..Default::default()
},
Config {
env: None,
test: Some(FileMatcher::Regex("\\.tsx$".into())),
exclude: None,
jsc: JscConfig {
syntax: Some(Syntax::Typescript(TsConfig {
tsx: true,
..Default::default()
})),
..Default::default()
},
..Default::default()
},
Config {
env: None,
test: Some(FileMatcher::Regex("\\.(cts|mts)$".into())),
exclude: None,
jsc: JscConfig {
syntax: Some(Syntax::Typescript(TsConfig {
tsx: false,
disallow_ambiguous_jsx_like: true,
..Default::default()
})),
..Default::default()
},
..Default::default()
},
Config {
env: None,
test: Some(FileMatcher::Regex("\\.ts$".into())),
exclude: None,
jsc: JscConfig {
syntax: Some(Syntax::Typescript(TsConfig {
tsx: false,
..Default::default()
})),
..Default::default()
},
..Default::default()
},
])
}
}
impl Rc {
/// This method returns `Ok(None)` if the file should be ignored.
pub fn into_config(self, filename: Option<&Path>) -> Result<Option<Config>, Error> {
let cs = match self {
Rc::Single(mut c) => match filename {
Some(filename) => {
if c.matches(filename)? {
c.adjust(filename);
return Ok(Some(c));
} else {
return Ok(None);
}
}
// TODO
None => return Ok(Some(c)),
},
Rc::Multi(cs) => cs,
};
match filename {
Some(filename) => {
for mut c in cs {
if c.matches(filename)? {
c.adjust(filename);
return Ok(Some(c));
}
}
}
None => return Ok(Some(Config::default())),
}
bail!(".swcrc exists but not matched")
}
}
/// A single object in the `.swcrc` file
#[derive(Debug, Default, Clone, Deserialize, Merge)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Config {
#[serde(default)]
pub env: Option<swc_ecma_preset_env::Config>,
#[serde(default)]
pub test: Option<FileMatcher>,
#[serde(default)]
pub exclude: Option<FileMatcher>,
#[serde(default)]
pub jsc: JscConfig,
#[serde(default)]
pub module: Option<ModuleConfig>,
#[serde(default)]
pub minify: BoolConfig<false>,
#[serde(default)]
pub input_source_map: Option<InputSourceMap>,
/// Possible values are: `'inline'`, `true`, `false`.
#[serde(default)]
pub source_maps: Option<SourceMapsConfig>,
#[serde(default)]
pub inline_sources_content: BoolConfig<true>,
#[serde(default)]
pub emit_source_map_columns: BoolConfig<true>,
#[serde(default)]
pub error: ErrorConfig,
#[serde(default)]
pub is_module: Option<IsModule>,
#[serde(rename = "$schema")]
pub schema: Option<String>,
}
impl Config {
/// Adjust config for `file`.
///
///
///
/// - typescript: `tsx` will be modified if file extension is `ts`.
pub fn adjust(&mut self, file: &Path) {
if let Some(Syntax::Typescript(TsConfig { tsx, dts, .. })) = &mut self.jsc.syntax {
let is_dts = file
.file_name()
.and_then(|f| f.to_str())
.map(|s| s.ends_with(".d.ts"))
.unwrap_or(false);
if is_dts {
*dts = true;
}
if file.extension() == Some("tsx".as_ref()) {
*tsx = true;
} else if file.extension() == Some("ts".as_ref()) {
*tsx = false;
}
}
}
}