-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathswc.rs
425 lines (405 loc) · 13.9 KB
/
swc.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
use crate::error::{DiagnosticBuffer, ErrorBuffer};
use crate::hmr::hmr;
use crate::minifier::{MinifierOptions, MinifierPass};
use crate::resolve_fold::resolve_fold;
use crate::resolver::{DependencyDescriptor, Resolver};
use std::{cell::RefCell, path::Path, rc::Rc};
use swc_common::comments::SingleThreadedComments;
use swc_common::errors::{Handler, HandlerFlags};
use swc_common::{chain, FileName, Globals, Mark, SourceMap};
use swc_ecma_transforms::optimization::simplify::dce;
use swc_ecma_transforms::pass::Optional;
use swc_ecma_transforms::proposals::decorators;
use swc_ecma_transforms::typescript::strip;
use swc_ecma_transforms::{compat, fixer, helpers, hygiene, react, Assumptions};
use swc_ecmascript::ast::{EsVersion, Module, Program};
use swc_ecmascript::codegen::text_writer::JsWriter;
use swc_ecmascript::parser::lexer::Lexer;
use swc_ecmascript::parser::{EsConfig, StringInput, Syntax, TsConfig};
use swc_ecmascript::visit::{as_folder, Fold, FoldWith};
/// Options for transpiling a module.
#[derive(Clone)]
pub struct EmitOptions {
pub target: EsVersion,
pub jsx: Option<String>,
pub jsx_pragma: Option<String>,
pub jsx_pragma_frag: Option<String>,
pub jsx_import_source: Option<String>,
pub react_refresh: bool,
pub strip_data_export: bool,
pub minify: Option<MinifierOptions>,
pub source_map: bool,
}
impl Default for EmitOptions {
fn default() -> Self {
EmitOptions {
target: EsVersion::Es2022,
jsx: None,
jsx_pragma: None,
jsx_pragma_frag: None,
jsx_import_source: None,
react_refresh: false,
strip_data_export: false,
minify: None,
source_map: false,
}
}
}
#[derive(Clone)]
pub struct SWC {
pub specifier: String,
pub module: Module,
pub source_map: Rc<SourceMap>,
pub comments: SingleThreadedComments,
}
impl SWC {
/// parse source code.
pub fn parse(specifier: &str, source: &str, target: EsVersion, lang: Option<String>) -> Result<Self, anyhow::Error> {
let source_map = SourceMap::default();
let source_file = source_map.new_source_file(FileName::Real(Path::new(specifier).to_path_buf()), source.into());
let sm = &source_map;
let error_buffer = ErrorBuffer::new(specifier);
let syntax = get_syntax(specifier, lang);
let input = StringInput::from(&*source_file);
let comments = SingleThreadedComments::default();
let lexer = Lexer::new(syntax, target, input, Some(&comments));
let mut parser = swc_ecmascript::parser::Parser::new_from(lexer);
let handler = Handler::with_emitter_and_flags(
Box::new(error_buffer.clone()),
HandlerFlags {
can_emit_warnings: true,
dont_buffer_diagnostics: true,
..HandlerFlags::default()
},
);
let module = parser
.parse_module()
.map_err(move |err| {
let mut diagnostic = err.into_diagnostic(&handler);
diagnostic.emit();
DiagnosticBuffer::from_error_buffer(error_buffer, |span| sm.lookup_char_pos(span.lo))
})
.unwrap();
Ok(SWC {
specifier: specifier.into(),
module,
source_map: Rc::new(source_map),
comments,
})
}
/// parse deps in the module.
pub fn parse_deps(&self, resolver: Rc<RefCell<Resolver>>) -> Result<Vec<DependencyDescriptor>, anyhow::Error> {
let program = Program::Module(self.module.clone());
let mut resolve_fold = resolve_fold(resolver.clone(), false, true);
program.fold_with(&mut resolve_fold);
let resolver = resolver.borrow();
Ok(resolver.deps.clone())
}
/// transform a JS/TS/JSX/TSX file into a JS file, based on the supplied options.
pub fn transform(
self,
resolver: Rc<RefCell<Resolver>>,
options: &EmitOptions,
) -> Result<(String, Option<String>), anyhow::Error> {
swc_common::GLOBALS.set(&Globals::new(), || {
let unresolved_mark = Mark::new();
let top_level_mark = Mark::fresh(Mark::root());
let specifier_is_remote = resolver.borrow().specifier_is_remote;
let extname = Path::new(&self.specifier)
.extension()
.unwrap_or_default()
.to_ascii_lowercase();
let is_dev = resolver.borrow().is_dev;
let is_ts = extname == "ts" || extname == "mts" || extname == "tsx";
let jsxt = options.jsx.as_deref().unwrap_or("classic");
let jsx_preserve = jsxt == "preserve";
let is_jsx = extname == "jsx" || extname == "tsx";
let react_options = if jsxt == "automatic" {
let mut resolver = resolver.borrow_mut();
let import_source = options.jsx_import_source.as_deref().unwrap_or("react");
let runtime = if is_dev { "/jsx-dev-runtime" } else { "/jsx-runtime" };
let import_source = resolver.resolve(&(import_source.to_owned() + runtime), false, None);
let import_source = import_source
.split("?")
.next()
.unwrap_or(&import_source)
.strip_suffix(runtime)
.unwrap_or(&import_source)
.to_string();
if !is_jsx {
resolver.deps.pop();
}
react::Options {
runtime: Some(react::Runtime::Automatic),
import_source: Some(import_source),
..Default::default()
}
} else {
react::Options {
pragma: options.jsx_pragma.clone(),
pragma_frag: options.jsx_pragma_frag.clone(),
..Default::default()
}
};
let assumptions = Assumptions::all();
let passes = chain!(
swc_ecma_transforms::resolver(unresolved_mark, top_level_mark, is_ts),
Optional::new(react::jsx_src(is_dev, self.source_map.clone()), is_jsx && is_dev),
resolve_fold(resolver.clone(), options.strip_data_export, false),
decorators::decorators(decorators::Config {
legacy: true,
emit_metadata: false,
use_define_for_class_fields: false,
}),
Optional::new(
compat::es2022::es2022(
Some(&self.comments),
compat::es2022::Config {
class_properties: compat::es2022::class_properties::Config {
private_as_properties: assumptions.private_fields_as_properties,
constant_super: assumptions.constant_super,
set_public_fields: assumptions.set_public_class_fields,
no_document_all: assumptions.no_document_all
}
}
),
should_enable(options.target, EsVersion::Es2022)
),
Optional::new(
compat::es2021::es2021(),
should_enable(options.target, EsVersion::Es2021)
),
Optional::new(
compat::es2020::es2020(compat::es2020::Config {
nullish_coalescing: compat::es2020::nullish_coalescing::Config {
no_document_all: assumptions.no_document_all
},
optional_chaining: compat::es2020::opt_chaining::Config {
no_document_all: assumptions.no_document_all,
pure_getter: assumptions.pure_getters
}
}),
should_enable(options.target, EsVersion::Es2020)
),
Optional::new(
compat::es2019::es2019(),
should_enable(options.target, EsVersion::Es2019)
),
Optional::new(
compat::es2018(compat::es2018::Config {
object_rest_spread: compat::es2018::object_rest_spread::Config {
no_symbol: assumptions.object_rest_no_symbols,
set_property: assumptions.set_spread_properties,
pure_getters: assumptions.pure_getters,
}
}),
should_enable(options.target, EsVersion::Es2018)
),
Optional::new(
compat::es2017(
compat::es2017::Config {
async_to_generator: compat::es2017::async_to_generator::Config {
ignore_function_name: assumptions.ignore_function_name,
ignore_function_length: assumptions.ignore_function_length
}
},
Some(&self.comments),
unresolved_mark,
),
should_enable(options.target, EsVersion::Es2017)
),
Optional::new(compat::es2016(), should_enable(options.target, EsVersion::Es2016)),
compat::reserved_words::reserved_words(),
helpers::inject_helpers(top_level_mark),
Optional::new(
strip::strip_with_config(strip_config_from_emit_options(), top_level_mark),
!is_jsx
),
Optional::new(
strip::strip_with_jsx(
self.source_map.clone(),
strip_config_from_emit_options(),
&self.comments,
top_level_mark
),
is_jsx
),
Optional::new(
react::refresh(
is_dev,
Some(react::RefreshOptions {
refresh_reg: "$RefreshReg$".into(),
refresh_sig: "$RefreshSig$".into(),
emit_full_signatures: false,
}),
self.source_map.clone(),
Some(&self.comments),
top_level_mark
),
options.react_refresh && !specifier_is_remote
),
Optional::new(
react::jsx(
self.source_map.clone(),
Some(&self.comments),
react::Options {
next: Some(true),
use_builtins: Some(true),
development: Some(is_dev),
..react_options
},
top_level_mark
),
is_jsx && !jsx_preserve
),
Optional::new(hmr(resolver.clone()), is_dev && !specifier_is_remote),
dce::dce(
dce::Config {
module_mark: None,
top_level: true,
top_retain: vec![],
preserve_imports_with_side_effects: false,
},
unresolved_mark
),
Optional::new(
as_folder(MinifierPass {
cm: self.source_map.clone(),
comments: Some(self.comments.clone()),
unresolved_mark,
top_level_mark,
options: options.minify.unwrap_or(MinifierOptions { compress: Some(false) }),
}),
options.minify.is_some()
),
hygiene::hygiene_with_config(hygiene::Config {
keep_class_names: true,
top_level_mark: top_level_mark,
..Default::default()
}),
fixer(Some(&self.comments)),
);
let (mut code, map) = self.emit(passes, options).unwrap();
// remove dead deps by tree-shaking
if options.strip_data_export {
let mut resolver = resolver.borrow_mut();
let mut deps: Vec<DependencyDescriptor> = Vec::new();
let a = code.split("\"").collect::<Vec<&str>>();
for dep in resolver.deps.clone() {
if dep.specifier.ends_with("/jsx-runtime")
|| dep.specifier.ends_with("/jsx-dev-runtime")
|| a.contains(&dep.import_url.as_str())
{
deps.push(dep);
}
}
resolver.deps = deps;
}
// resolve jsx-runtime url
let mut jsx_runtime = None;
let resolver = resolver.borrow();
for dep in &resolver.deps {
if dep.specifier.ends_with("/jsx-runtime") || dep.specifier.ends_with("/jsx-dev-runtime") {
jsx_runtime = Some((dep.specifier.clone(), dep.import_url.clone()));
break;
}
}
if let Some((jsx_runtime, import_url)) = jsx_runtime {
code = code.replace(
format!("\"{}\"", jsx_runtime).as_str(),
format!("\"{}\"", import_url).as_str(),
);
}
Ok((code, map))
})
}
/// Apply transform with the fold.
pub fn emit<T: Fold>(&self, mut fold: T, options: &EmitOptions) -> Result<(String, Option<String>), anyhow::Error> {
let program = Program::Module(self.module.clone());
let program = helpers::HELPERS.set(&helpers::Helpers::new(false), || program.fold_with(&mut fold));
let mut buf = Vec::new();
let mut src_map_buf = Vec::new();
let src_map = if options.source_map {
Some(&mut src_map_buf)
} else {
None
};
{
let writer = Box::new(JsWriter::new(self.source_map.clone(), "\n", &mut buf, src_map));
let mut emitter = swc_ecmascript::codegen::Emitter {
cfg: swc_ecmascript::codegen::Config {
target: options.target,
minify: options.minify.is_some(),
..Default::default()
},
comments: Some(&self.comments),
cm: self.source_map.clone(),
wr: writer,
};
emitter.emit_program(&program).unwrap();
}
// output
let src = String::from_utf8(buf).unwrap();
if options.source_map {
let mut buf = Vec::new();
self
.source_map
.build_source_map_from(&mut src_map_buf, None)
.to_writer(&mut buf)
.unwrap();
Ok((src, Some(String::from_utf8(buf).unwrap())))
} else {
Ok((src, None))
}
}
}
fn get_es_config(jsx: bool) -> EsConfig {
EsConfig {
fn_bind: true,
export_default_from: true,
import_assertions: true,
allow_super_outside_method: true,
allow_return_outside_function: true,
jsx,
..EsConfig::default()
}
}
fn get_ts_config(tsx: bool) -> TsConfig {
TsConfig {
decorators: true,
tsx,
..TsConfig::default()
}
}
fn get_syntax(specifier: &str, lang: Option<String>) -> Syntax {
let lang = if let Some(lang) = lang {
lang
} else {
specifier
.split(|c| c == '?' || c == '#')
.next()
.unwrap()
.split('.')
.last()
.unwrap_or("js")
.to_lowercase()
};
match lang.as_str() {
"js" | "mjs" => Syntax::Es(get_es_config(false)),
"jsx" => Syntax::Es(get_es_config(true)),
"ts" | "mts" => Syntax::Typescript(get_ts_config(false)),
"tsx" => Syntax::Typescript(get_ts_config(true)),
_ => Syntax::Es(get_es_config(false)),
}
}
fn strip_config_from_emit_options() -> strip::Config {
strip::Config {
import_not_used_as_values: strip::ImportsNotUsedAsValues::Remove,
use_define_for_class_fields: true,
no_empty_export: true,
..Default::default()
}
}
fn should_enable(target: EsVersion, feature: EsVersion) -> bool {
target < feature
}