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
#![deny(clippy::all)]
#![deny(clippy::all)]
#![deny(unused)]
#![allow(clippy::result_unit_err)]

use std::{
    env,
    fs::{self, create_dir_all, read_to_string, OpenOptions},
    io::Write,
    mem::take,
    path::Path,
    process::Command,
    rc::Rc,
};

use ansi_term::Color;
use anyhow::Error;
use serde::de::DeserializeOwned;
use sha1::{Digest, Sha1};
use swc_common::{
    chain,
    comments::SingleThreadedComments,
    errors::{Handler, HANDLER},
    source_map::SourceMapGenConfig,
    sync::Lrc,
    util::take::Take,
    FileName, Mark, SourceMap, DUMMY_SP,
};
use swc_ecma_ast::{Pat, *};
use swc_ecma_codegen::Emitter;
use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax};
use swc_ecma_testing::{exec_node_js, JsExecOptions};
use swc_ecma_transforms_base::{
    fixer,
    helpers::{inject_helpers, HELPERS},
    hygiene,
    pass::noop,
};
use swc_ecma_utils::{quote_ident, quote_str, ExprFactory};
use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, FoldWith, VisitMut, VisitMutWith};
use tempfile::tempdir_in;
use testing::{assert_eq, find_executable, NormalizedOutput};

pub struct Tester<'a> {
    pub cm: Lrc<SourceMap>,
    pub handler: &'a Handler,
    /// This will be changed to [SingleThreadedComments] once `cargo-mono`
    /// supports correct bumping logic, or we need to make a breaking change in
    /// a upstream crate of this crate.
    ///
    /// Although type is `Rc<SingleThreadedComments>`, it's fine to clone
    /// `SingleThreadedComments` without `Rc`.
    pub comments: Rc<SingleThreadedComments>,
}

impl<'a> Tester<'a> {
    pub fn run<F, Ret>(op: F) -> Ret
    where
        F: FnOnce(&mut Tester<'_>) -> Result<Ret, ()>,
    {
        let out = ::testing::run_test(false, |cm, handler| {
            HANDLER.set(handler, || {
                HELPERS.set(&Default::default(), || {
                    op(&mut Tester {
                        cm,
                        handler,
                        comments: Default::default(),
                    })
                })
            })
        });

        match out {
            Ok(ret) => ret,
            Err(stderr) => panic!("Stderr:\n{}", stderr),
        }
    }

    pub(crate) fn run_captured<F, T>(op: F) -> (Option<T>, NormalizedOutput)
    where
        F: FnOnce(&mut Tester<'_>) -> Result<T, ()>,
    {
        let mut res = None;
        let output = ::testing::Tester::new().print_errors(|cm, handler| -> Result<(), _> {
            HANDLER.set(&handler, || {
                HELPERS.set(&Default::default(), || {
                    let result = op(&mut Tester {
                        cm,
                        handler: &handler,
                        comments: Default::default(),
                    });

                    res = result.ok();

                    // We need stderr
                    Err(())
                })
            })
        });

        let output = output
            .err()
            .unwrap_or_else(|| NormalizedOutput::from(String::from("")));

        (res, output)
    }

    pub fn with_parser<F, T>(
        &mut self,
        file_name: &str,
        syntax: Syntax,
        src: &str,
        op: F,
    ) -> Result<T, ()>
    where
        F: FnOnce(&mut Parser<Lexer>) -> Result<T, swc_ecma_parser::error::Error>,
    {
        let fm = self
            .cm
            .new_source_file(FileName::Real(file_name.into()), src.into());

        let mut p = Parser::new(syntax, StringInput::from(&*fm), Some(&self.comments));
        let res = op(&mut p).map_err(|e| e.into_diagnostic(self.handler).emit());

        for e in p.take_errors() {
            e.into_diagnostic(self.handler).emit()
        }

        res
    }

    pub fn parse_module(&mut self, file_name: &str, src: &str) -> Result<Module, ()> {
        self.with_parser(file_name, Syntax::default(), src, |p| p.parse_module())
    }

    pub fn parse_stmts(&mut self, file_name: &str, src: &str) -> Result<Vec<Stmt>, ()> {
        let stmts = self.with_parser(file_name, Syntax::default(), src, |p| {
            p.parse_script().map(|script| script.body)
        })?;

        Ok(stmts)
    }

    pub fn parse_stmt(&mut self, file_name: &str, src: &str) -> Result<Stmt, ()> {
        let mut stmts = self.parse_stmts(file_name, src)?;
        assert!(stmts.len() == 1);

        Ok(stmts.pop().unwrap())
    }

    pub fn apply_transform<T: Fold>(
        &mut self,
        mut tr: T,
        name: &str,
        syntax: Syntax,
        src: &str,
    ) -> Result<Module, ()> {
        let fm = self
            .cm
            .new_source_file(FileName::Real(name.into()), src.into());

        let module = {
            let mut p = Parser::new_from(Lexer::new(
                syntax,
                EsVersion::latest(),
                StringInput::from(&*fm),
                Some(&self.comments),
            ));
            let res = p
                .parse_module()
                .map_err(|e| e.into_diagnostic(self.handler).emit());

            for e in p.take_errors() {
                e.into_diagnostic(self.handler).emit()
            }

            res?
        };

        let module = Program::Module(module)
            .fold_with(&mut tr)
            .fold_with(&mut as_folder(Normalizer));

        Ok(module.expect_module())
    }

    pub fn print(&mut self, module: &Module, comments: &Rc<SingleThreadedComments>) -> String {
        let mut buf = vec![];
        {
            let mut emitter = Emitter {
                cfg: Default::default(),
                cm: self.cm.clone(),
                wr: Box::new(swc_ecma_codegen::text_writer::JsWriter::new(
                    self.cm.clone(),
                    "\n",
                    &mut buf,
                    None,
                )),
                comments: Some(comments),
            };

            // println!("Emitting: {:?}", module);
            emitter.emit_module(module).unwrap();
        }

        let s = String::from_utf8_lossy(&buf);
        s.to_string()
    }
}

struct RegeneratorHandler;

impl VisitMut for RegeneratorHandler {
    noop_visit_mut_type!();

    fn visit_mut_module_item(&mut self, item: &mut ModuleItem) {
        if let ModuleItem::ModuleDecl(ModuleDecl::Import(import)) = item {
            if &*import.src.value != "regenerator-runtime" {
                return;
            }

            let s = import.specifiers.iter().find_map(|v| match v {
                ImportSpecifier::Default(rt) => Some(rt.local.clone()),
                _ => None,
            });

            let s = match s {
                Some(v) => v,
                _ => return,
            };

            let init = Box::new(Expr::Call(CallExpr {
                span: DUMMY_SP,
                callee: quote_ident!("require").as_callee(),
                args: vec![quote_str!("regenerator-runtime").as_arg()],
                type_args: Default::default(),
            }));

            let decl = VarDeclarator {
                span: DUMMY_SP,
                name: s.into(),
                init: Some(init),
                definite: Default::default(),
            };
            *item = ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl {
                span: import.span,
                kind: VarDeclKind::Var,
                declare: false,
                decls: vec![decl],
            }))))
        }
    }
}

fn make_tr<F, P>(op: F, tester: &mut Tester<'_>) -> impl Fold
where
    F: FnOnce(&mut Tester<'_>) -> P,
    P: Fold,
{
    chain!(op(tester), as_folder(RegeneratorHandler))
}

#[track_caller]
pub fn test_transform<F, P>(
    syntax: Syntax,
    tr: F,
    input: &str,
    expected: &str,
    _always_ok_if_code_eq: bool,
) where
    F: FnOnce(&mut Tester) -> P,
    P: Fold,
{
    Tester::run(|tester| {
        let expected = tester.apply_transform(
            as_folder(::swc_ecma_utils::DropSpan {
                preserve_ctxt: true,
            }),
            "output.js",
            syntax,
            expected,
        )?;

        let expected_comments = take(&mut tester.comments);

        println!("----- Actual -----");

        let tr = make_tr(tr, tester);
        let actual = tester.apply_transform(tr, "input.js", syntax, input)?;

        match ::std::env::var("PRINT_HYGIENE") {
            Ok(ref s) if s == "1" => {
                let hygiene_src = tester.print(
                    &actual.clone().fold_with(&mut HygieneVisualizer),
                    &tester.comments.clone(),
                );
                println!("----- Hygiene -----\n{}", hygiene_src);
            }
            _ => {}
        }

        let actual = actual
            .fold_with(&mut as_folder(::swc_ecma_utils::DropSpan {
                preserve_ctxt: true,
            }))
            .fold_with(&mut hygiene::hygiene())
            .fold_with(&mut fixer::fixer(Some(&tester.comments)));

        println!("{:?}", tester.comments);
        println!("{:?}", expected_comments);

        {
            let (actual_leading, actual_trailing) = tester.comments.borrow_all();
            let (expected_leading, expected_trailing) = expected_comments.borrow_all();

            if actual == expected
                && *actual_leading == *expected_leading
                && *actual_trailing == *expected_trailing
            {
                return Ok(());
            }
        }

        let (actual_src, expected_src) = (
            tester.print(&actual, &tester.comments.clone()),
            tester.print(&expected, &expected_comments),
        );

        if actual_src == expected_src {
            return Ok(());
        }

        println!(">>>>> {} <<<<<\n{}", Color::Green.paint("Orig"), input);
        println!(">>>>> {} <<<<<\n{}", Color::Green.paint("Code"), actual_src);

        if actual_src != expected_src {
            panic!(
                r#"assertion failed: `(left == right)`
            {}"#,
                ::testing::diff(&actual_src, &expected_src),
            );
        }

        Err(())
    });
}

/// Test transformation.
#[macro_export]
macro_rules! test {
    (ignore, $syntax:expr, $tr:expr, $test_name:ident, $input:expr, $expected:expr) => {
        #[test]
        #[ignore]
        fn $test_name() {
            $crate::test_transform($syntax, $tr, $input, $expected, false)
        }
    };

    ($syntax:expr, $tr:expr, $test_name:ident, $input:expr, $expected:expr) => {
        #[test]
        fn $test_name() {
            $crate::test_transform($syntax, $tr, $input, $expected, false)
        }
    };

    ($syntax:expr, $tr:expr, $test_name:ident, $input:expr, $expected:expr, ok_if_code_eq) => {
        #[test]
        fn $test_name() {
            $crate::test_transform($syntax, $tr, $input, $expected, true)
        }
    };
}

/// Execute `node` for `input` and ensure that it prints same output after
/// transformation.
pub fn compare_stdout<F, P>(syntax: Syntax, tr: F, input: &str)
where
    F: FnOnce(&mut Tester<'_>) -> P,
    P: Fold,
{
    Tester::run(|tester| {
        let tr = make_tr(tr, tester);

        let module = tester.apply_transform(tr, "input.js", syntax, input)?;

        match ::std::env::var("PRINT_HYGIENE") {
            Ok(ref s) if s == "1" => {
                let hygiene_src = tester.print(
                    &module.clone().fold_with(&mut HygieneVisualizer),
                    &tester.comments.clone(),
                );
                println!("----- Hygiene -----\n{}", hygiene_src);
            }
            _ => {}
        }

        let mut module = module
            .fold_with(&mut hygiene::hygiene())
            .fold_with(&mut fixer::fixer(Some(&tester.comments)));

        let src_without_helpers = tester.print(&module, &tester.comments.clone());
        module = module.fold_with(&mut inject_helpers(Mark::fresh(Mark::root())));

        let transformed_src = tester.print(&module, &tester.comments.clone());

        println!(
            "\t>>>>> Orig <<<<<\n{}\n\t>>>>> Code <<<<<\n{}",
            input, src_without_helpers
        );

        let expected = stdout_of(input).unwrap();

        println!("\t>>>>> Expected stdout <<<<<\n{}", expected);

        let actual = stdout_of(&transformed_src).unwrap();

        assert_eq!(expected, actual);

        Ok(())
    })
}

/// Execute `jest` after transpiling `input` using `tr`.
pub fn exec_tr<F, P>(test_name: &str, syntax: Syntax, tr: F, input: &str)
where
    F: FnOnce(&mut Tester<'_>) -> P,
    P: Fold,
{
    Tester::run(|tester| {
        let tr = make_tr(tr, tester);

        let module = tester.apply_transform(
            tr,
            "input.js",
            syntax,
            &format!(
                "it('should work', async function () {{
                    {}
                }})",
                input
            ),
        )?;
        match ::std::env::var("PRINT_HYGIENE") {
            Ok(ref s) if s == "1" => {
                let hygiene_src = tester.print(
                    &module.clone().fold_with(&mut HygieneVisualizer),
                    &tester.comments.clone(),
                );
                println!("----- Hygiene -----\n{}", hygiene_src);
            }
            _ => {}
        }

        let mut module = module
            .fold_with(&mut hygiene::hygiene())
            .fold_with(&mut fixer::fixer(Some(&tester.comments)));

        let src_without_helpers = tester.print(&module, &tester.comments.clone());
        module = module.fold_with(&mut inject_helpers(Mark::fresh(Mark::root())));

        let src = tester.print(&module, &tester.comments.clone());

        println!(
            "\t>>>>> {} <<<<<\n{}\n\t>>>>> {} <<<<<\n{}",
            Color::Green.paint("Orig"),
            input,
            Color::Green.paint("Code"),
            src_without_helpers
        );

        exec_with_node_test_runner(test_name, &src)
    })
}

fn calc_hash(s: &str) -> String {
    let mut hasher = Sha1::new();
    hasher.update(s.as_bytes());
    let sum = hasher.finalize();

    hex::encode(sum)
}

fn exec_with_node_test_runner(test_name: &str, src: &str) -> Result<(), ()> {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("target")
        .join("testing")
        .join(test_name);

    create_dir_all(&root).expect("failed to create parent directory for temp directory");

    let hash = calc_hash(src);
    let success_cache = root.join(format!("{}.success", hash));

    if env::var("SWC_CACHE_TEST").unwrap_or_default() == "1" {
        println!("Trying cache as `SWC_CACHE_TEST` is `1`");

        if success_cache.exists() {
            println!("Cache: success");
            return Ok(());
        }
    }

    let tmp_dir = tempdir_in(&root).expect("failed to create a temp directory");
    create_dir_all(&tmp_dir).unwrap();

    let path = tmp_dir.path().join(format!("{}.test.js", test_name));

    let mut tmp = OpenOptions::new()
        .create(true)
        .write(true)
        .open(&path)
        .expect("failed to create a temp file");
    write!(tmp, "{}", src).expect("failed to write to temp file");
    tmp.flush().unwrap();

    let test_runner_path = find_executable("mocha").expect("failed to find `mocha` from path");

    let mut base_cmd = if cfg!(target_os = "windows") {
        let mut c = Command::new("cmd");
        c.arg("/C").arg(&test_runner_path);
        c
    } else {
        Command::new(&test_runner_path)
    };

    let output = base_cmd
        .arg(&format!("{}", path.display()))
        .arg("--color")
        .current_dir(root)
        .output()
        .expect("failed to run mocha");

    println!(">>>>> {} <<<<<", Color::Red.paint("Stdout"));
    println!("{}", String::from_utf8_lossy(&output.stdout));
    println!(">>>>> {} <<<<<", Color::Red.paint("Stderr"));
    println!("{}", String::from_utf8_lossy(&output.stderr));

    if output.status.success() {
        fs::write(&success_cache, "").unwrap();
        return Ok(());
    }
    let dir_name = path.display().to_string();
    ::std::mem::forget(tmp_dir);
    panic!("Execution failed: {dir_name}")
}

fn stdout_of(code: &str) -> Result<String, Error> {
    exec_node_js(
        code,
        JsExecOptions {
            cache: true,
            module: false,
            ..Default::default()
        },
    )
}

/// Test transformation.
#[macro_export]
macro_rules! test_exec {
    (ignore, $syntax:expr, $tr:expr, $test_name:ident, $input:expr) => {
        #[test]
        #[ignore]
        fn $test_name() {
            $crate::exec_tr(stringify!($test_name), $syntax, $tr, $input)
        }
    };

    ($syntax:expr, $tr:expr, $test_name:ident, $input:expr) => {
        #[test]
        fn $test_name() {
            if ::std::env::var("EXEC").unwrap_or(String::from("")) == "0" {
                return;
            }

            $crate::exec_tr(stringify!($test_name), $syntax, $tr, $input)
        }
    };
}

/// Test transformation by invoking it using `node`. The code must print
/// something to stdout.
#[macro_export]
macro_rules! compare_stdout {
    ($syntax:expr, $tr:expr, $test_name:ident, $input:expr) => {
        #[test]
        fn $test_name() {
            $crate::compare_stdout($syntax, $tr, $input)
        }
    };
}

struct Normalizer;
impl VisitMut for Normalizer {
    fn visit_mut_pat_or_expr(&mut self, node: &mut PatOrExpr) {
        node.visit_mut_children_with(self);

        if let PatOrExpr::Pat(pat) = node {
            if let Pat::Expr(e) = &mut **pat {
                *node = PatOrExpr::Expr(e.take());
            }
        }
    }
}

/// Converts `foo#1` to `foo__1` so it can be verified by the test.
pub struct HygieneTester;
impl Fold for HygieneTester {
    fn fold_ident(&mut self, ident: Ident) -> Ident {
        Ident {
            sym: format!("{}__{}", ident.sym, ident.span.ctxt.as_u32()).into(),
            ..ident
        }
    }

    fn fold_member_prop(&mut self, p: MemberProp) -> MemberProp {
        match p {
            MemberProp::Computed(..) => p.fold_children_with(self),
            _ => p,
        }
    }

    fn fold_prop_name(&mut self, p: PropName) -> PropName {
        match p {
            PropName::Computed(..) => p.fold_children_with(self),
            _ => p,
        }
    }
}

pub struct HygieneVisualizer;
impl Fold for HygieneVisualizer {
    fn fold_ident(&mut self, ident: Ident) -> Ident {
        Ident {
            sym: format!("{}{:?}", ident.sym, ident.span.ctxt()).into(),
            ..ident
        }
    }
}

/// Just like babel, walk up the directory tree and find a file named
/// `options.json`.
pub fn parse_options<T>(dir: &Path) -> T
where
    T: DeserializeOwned,
{
    let mut s = String::from("{}");

    fn check(dir: &Path) -> Option<String> {
        let file = dir.join("options.json");
        if let Ok(v) = read_to_string(&file) {
            eprintln!("Using options.json at {}", file.display());
            eprintln!("----- {} -----\n{}", Color::Green.paint("Options"), v);

            return Some(v);
        }

        dir.parent().and_then(check)
    }

    if let Some(content) = check(dir) {
        s = content;
    }

    serde_json::from_str(&s)
        .unwrap_or_else(|err| panic!("failed to deserialize options.json: {}\n{}", err, s))
}

/// Config for [test_fixture]. See [test_fixture] for documentation.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FixtureTestConfig {
    /// If true, source map will be printed to the `.map` file.
    ///
    /// Defaults to false.
    pub sourcemap: bool,

    /// If true, diagnostics written to [HANDLER] will be printed as a fixture,
    /// with `.stderr` extension.
    ///
    /// If false, test will fail if diagnostics are emitted.
    ///
    /// Defaults to false.
    pub allow_error: bool,
}

/// You can do `UPDATE=1 cargo test` to update fixtures.
pub fn test_fixture<P>(
    syntax: Syntax,
    tr: &dyn Fn(&mut Tester) -> P,
    input: &Path,
    output: &Path,
    config: FixtureTestConfig,
) where
    P: Fold,
{
    let _logger = testing::init();

    let expected = read_to_string(output);
    let _is_really_expected = expected.is_ok();
    let expected = expected.unwrap_or_default();

    let expected_src = Tester::run(|tester| {
        let expected_module = tester.apply_transform(noop(), "expected.js", syntax, &expected)?;

        let expected_src = tester.print(&expected_module, &tester.comments.clone());

        println!(
            "----- {} -----\n{}",
            Color::Green.paint("Expected"),
            expected_src
        );

        Ok(expected_src)
    });

    let mut src_map = if config.sourcemap { Some(vec![]) } else { None };

    let mut sourcemap = None;

    let (actual_src, stderr) = Tester::run_captured(|tester| {
        let input_str = read_to_string(input).unwrap();
        println!("----- {} -----\n{}", Color::Green.paint("Input"), input_str);

        let tr = tr(tester);

        println!("----- {} -----", Color::Green.paint("Actual"));

        let actual =
            tester.apply_transform(tr, "input.js", syntax, &read_to_string(input).unwrap())?;

        match ::std::env::var("PRINT_HYGIENE") {
            Ok(ref s) if s == "1" => {
                let hygiene_src = tester.print(
                    &actual.clone().fold_with(&mut HygieneVisualizer),
                    &tester.comments.clone(),
                );
                println!(
                    "----- {} -----\n{}",
                    Color::Green.paint("Hygiene"),
                    hygiene_src
                );
            }
            _ => {}
        }

        let actual = actual
            .fold_with(&mut crate::hygiene::hygiene())
            .fold_with(&mut crate::fixer::fixer(Some(&tester.comments)));

        let actual_src = {
            let module = &actual;
            let comments: &Rc<SingleThreadedComments> = &tester.comments.clone();
            let mut buf = vec![];
            {
                let mut emitter = Emitter {
                    cfg: Default::default(),
                    cm: tester.cm.clone(),
                    wr: Box::new(swc_ecma_codegen::text_writer::JsWriter::new(
                        tester.cm.clone(),
                        "\n",
                        &mut buf,
                        src_map.as_mut(),
                    )),
                    comments: Some(comments),
                };

                // println!("Emitting: {:?}", module);
                emitter.emit_module(module).unwrap();
            }

            if let Some(src_map) = &mut src_map {
                sourcemap = Some(tester.cm.build_source_map_with_config(
                    src_map,
                    None,
                    SourceMapConfigImpl,
                ));
            }

            let s = String::from_utf8_lossy(&buf);
            s.to_string()
        };

        Ok(actual_src)
    });

    if config.allow_error {
        stderr
            .compare_to_file(output.with_extension("stderr"))
            .unwrap();
    } else if !stderr.is_empty() {
        panic!("stderr: {}", stderr);
    }

    if let Some(actual_src) = actual_src {
        println!("{}", actual_src);

        if let Some(sourcemap) = &sourcemap {
            println!("----- ----- ----- ----- -----");
            println!("SourceMap: {}", visualizer_url(&actual_src, sourcemap));
        }

        if actual_src != expected_src {
            NormalizedOutput::from(actual_src)
                .compare_to_file(output)
                .unwrap();
        }
    }

    if let Some(sourcemap) = sourcemap {
        let map = {
            let mut buf = vec![];
            sourcemap.to_writer(&mut buf).unwrap();
            String::from_utf8(buf).unwrap()
        };
        NormalizedOutput::from(map)
            .compare_to_file(output.with_extension("map"))
            .unwrap();
    }
}

/// Creates a url for https://evanw.github.io/source-map-visualization/
fn visualizer_url(code: &str, map: &sourcemap::SourceMap) -> String {
    let map = {
        let mut buf = vec![];
        map.to_writer(&mut buf).unwrap();
        String::from_utf8(buf).unwrap()
    };

    let code_len = format!("{}\0", code.len());
    let map_len = format!("{}\0", map.len());
    let hash = base64::encode(format!("{}{}{}{}", code_len, code, map_len, map));

    format!("https://evanw.github.io/source-map-visualization/#{}", hash)
}

struct SourceMapConfigImpl;

impl SourceMapGenConfig for SourceMapConfigImpl {
    fn file_name_to_source(&self, f: &swc_common::FileName) -> String {
        f.to_string()
    }

    fn inline_sources_content(&self, _: &swc_common::FileName) -> bool {
        true
    }
}