swc_ecma_transforms_testing/
lib.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
#![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, transmute},
    panic,
    path::{Path, PathBuf},
    process::Command,
    rc::Rc,
};

use ansi_term::Color;
use anyhow::Error;
use base64::prelude::{Engine, BASE64_STANDARD};
use serde::de::DeserializeOwned;
use sha2::{Digest, Sha256};
use swc_common::{
    comments::{Comments, SingleThreadedComments},
    errors::{Handler, HANDLER},
    source_map::SourceMapGenConfig,
    sync::Lrc,
    FileName, Mark, SourceMap, DUMMY_SP,
};
use swc_ecma_ast::*;
use swc_ecma_codegen::to_code_default;
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,
};
use swc_ecma_utils::{quote_ident, quote_str, ExprFactory};
use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, Fold, FoldWith, VisitMut};
use tempfile::tempdir_in;
use testing::{
    assert_eq, find_executable, NormalizedOutput, CARGO_TARGET_DIR, CARGO_WORKSPACE_ROOT,
};

pub mod babel_like;

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 Tester<'_> {
    pub fn run<F, Ret>(op: F) -> Ret
    where
        F: FnOnce(&mut Tester<'_>) -> Result<Ret, ()>,
    {
        let comments = Rc::new(SingleThreadedComments::default());

        let out = ::testing::run_test(false, |cm, handler| {
            HANDLER.set(handler, || {
                HELPERS.set(&Default::default(), || {
                    let cmts = comments.clone();
                    let c = Box::new(unsafe {
                        // Safety: This is unsafe but it's used only for testing.
                        transmute::<&dyn Comments, &'static dyn Comments>(&*cmts)
                    }) as Box<dyn Comments>;
                    swc_common::comments::COMMENTS.set(&c, || {
                        op(&mut Tester {
                            cm,
                            handler,
                            comments,
                        })
                    })
                })
            })
        });

        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()).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: Pass>(
        &mut self,
        tr: T,
        name: &str,
        syntax: Syntax,
        is_module: Option<bool>,
        src: &str,
    ) -> Result<Program, ()> {
        let program =
            self.with_parser(
                name,
                syntax,
                src,
                |parser: &mut Parser<Lexer>| match is_module {
                    Some(true) => parser.parse_module().map(Program::Module),
                    Some(false) => parser.parse_script().map(Program::Script),
                    None => parser.parse_program(),
                },
            )?;

        Ok(program.apply(tr))
    }

    pub fn print(&mut self, program: &Program, comments: &Rc<SingleThreadedComments>) -> String {
        to_code_default(self.cm.clone(), Some(comments), program)
    }
}

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 = CallExpr {
                span: DUMMY_SP,
                callee: quote_ident!("require").as_callee(),
                args: vec![quote_str!("regenerator-runtime").as_arg()],
                ..Default::default()
            }
            .into();

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

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

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

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

        let tr = (tr(tester), visit_mut_pass(RegeneratorHandler));
        let actual = tester.apply_transform(tr, "input.js", syntax, is_module, 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
            .apply(::swc_ecma_utils::DropSpan)
            .apply(hygiene::hygiene())
            .apply(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(())
    });
}

/// NOT A PUBLIC API. DO NOT USE.
#[doc(hidden)]
#[track_caller]
pub fn test_inline_input_output<F, P>(
    syntax: Syntax,
    is_module: Option<bool>,
    tr: F,
    input: &str,
    output: &str,
) where
    F: FnOnce(&mut Tester) -> P,
    P: Pass,
{
    let _logger = testing::init();

    let expected = output;

    let expected_src = Tester::run(|tester| {
        let expected_program =
            tester.apply_transform(noop_pass(), "expected.js", syntax, is_module, expected)?;

        let expected_src = tester.print(&expected_program, &Default::default());

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

        Ok(expected_src)
    });

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

        let tr = tr(tester);

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

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

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

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

        let actual_src = tester.print(&actual, &Default::default());

        Ok(actual_src)
    })
    .0
    .unwrap();

    assert_eq!(
        expected_src, actual_src,
        "Exepcted:\n{expected_src}\nActual:\n{actual_src}\n",
    );
}

/// NOT A PUBLIC API. DO NOT USE.
#[doc(hidden)]
#[track_caller]
pub fn test_inlined_transform<F, P>(
    test_name: &str,
    syntax: Syntax,
    module: Option<bool>,
    tr: F,
    input: &str,
) where
    F: FnOnce(&mut Tester) -> P,
    P: Pass,
{
    let loc = panic::Location::caller();

    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));

    let test_file_path = CARGO_WORKSPACE_ROOT.join(loc.file());

    let snapshot_dir = manifest_dir.join("tests").join("__swc_snapshots__").join(
        test_file_path
            .strip_prefix(&manifest_dir)
            .expect("test_inlined_transform does not support paths outside of the crate root"),
    );

    test_fixture_inner(
        syntax,
        Box::new(move |tester| Box::new(tr(tester))),
        input,
        &snapshot_dir.join(format!("{test_name}.js")),
        FixtureTestConfig {
            module,
            ..Default::default()
        },
    )
}

/// NOT A PUBLIC API. DO NOT USE.
#[doc(hidden)]
#[macro_export]
macro_rules! test_location {
    () => {{
        $crate::TestLocation {}
    }};
}

#[macro_export]
macro_rules! test_inline {
    (ignore, $syntax:expr, $tr:expr, $test_name:ident, $input:expr, $output:expr) => {
        #[test]
        #[ignore]
        fn $test_name() {
            $crate::test_inline_input_output($syntax, None, $tr, $input, $output)
        }
    };

    ($syntax:expr, $tr:expr, $test_name:ident, $input:expr, $output:expr) => {
        #[test]
        fn $test_name() {
            $crate::test_inline_input_output($syntax, None, $tr, $input, $output)
        }
    };
}

test_inline!(
    ignore,
    Syntax::default(),
    |_| noop_pass(),
    test_inline_ignored,
    "class Foo {}",
    "class Foo {}"
);

test_inline!(
    Syntax::default(),
    |_| noop_pass(),
    test_inline_pass,
    "class Foo {}",
    "class Foo {}"
);

#[test]
#[should_panic]
fn test_inline_should_fail() {
    test_inline_input_output(
        Default::default(),
        None,
        |_| noop_pass(),
        "class Foo {}",
        "",
    );
}

#[macro_export]
macro_rules! test {
    (ignore, $syntax:expr, $tr:expr, $test_name:ident, $input:expr) => {
        #[test]
        #[ignore]
        fn $test_name() {
            $crate::test_inlined_transform(stringify!($test_name), $syntax, None, $tr, $input)
        }
    };

    ($syntax:expr, $tr:expr, $test_name:ident, $input:expr) => {
        #[test]
        fn $test_name() {
            $crate::test_inlined_transform(stringify!($test_name), $syntax, None, $tr, $input)
        }
    };

    (module, $syntax:expr, $tr:expr, $test_name:ident, $input:expr) => {
        #[test]
        fn $test_name() {
            $crate::test_inlined_transform(stringify!($test_name), $syntax, Some(true), $tr, $input)
        }
    };

    (script, $syntax:expr, $tr:expr, $test_name:ident, $input:expr) => {
        #[test]
        fn $test_name() {
            $crate::test_inlined_script_transform(
                stringify!($test_name),
                $syntax,
                Some(false),
                $tr,
                $input,
            )
        }
    };

    ($syntax:expr, $tr:expr, $test_name:ident, $input:expr, ok_if_code_eq) => {
        #[test]
        fn $test_name() {
            $crate::test_inlined_transform(stringify!($test_name), $syntax, None, $tr, $input)
        }
    };
}

/// 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: Pass,
{
    Tester::run(|tester| {
        let tr = (tr(tester), visit_mut_pass(RegeneratorHandler));

        let program = tester.apply_transform(tr, "input.js", syntax, Some(true), input)?;

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

        let mut program = program
            .apply(hygiene::hygiene())
            .apply(fixer::fixer(Some(&tester.comments)));

        let src_without_helpers = tester.print(&program, &tester.comments.clone());
        program = program.apply(inject_helpers(Mark::fresh(Mark::root())));

        let transformed_src = tester.print(&program, &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: Pass,
{
    Tester::run(|tester| {
        let tr = (tr(tester), visit_mut_pass(RegeneratorHandler));

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

        let mut program = program
            .apply(hygiene::hygiene())
            .apply(fixer::fixer(Some(&tester.comments)));

        let src_without_helpers = tester.print(&program, &tester.comments.clone());
        program = program.apply(inject_helpers(Mark::fresh(Mark::root())));

        let src = tester.print(&program, &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(&src).map(|_| {})
    })
}

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

    hex::encode(sum)
}

fn exec_with_node_test_runner(src: &str) -> Result<(), ()> {
    let root = CARGO_TARGET_DIR.join("swc-es-exec-testing");

    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", hash));

    let mut tmp = OpenOptions::new()
        .create(true)
        .truncate(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 {
    (@check) => {
        if ::std::env::var("EXEC").unwrap_or(String::from("")) == "0" {
            return;
        }
    };

    (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() {
            test_exec!(@check);
            $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)
        }
    };
}

/// 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.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.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,
{
    type Map = serde_json::Map<String, serde_json::Value>;

    let mut value = Map::default();

    fn check(dir: &Path) -> Option<Map> {
        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(serde_json::from_str(&v).unwrap_or_else(|err| {
                panic!("failed to deserialize options.json: {}\n{}", err, v)
            }));
        }

        None
    }

    let mut c = Some(dir);

    while let Some(dir) = c {
        if let Some(new) = check(dir) {
            for (k, v) in new {
                if !value.contains_key(&k) {
                    value.insert(k, v);
                }
            }
        }

        c = dir.parent();
    }

    serde_json::from_value(serde_json::Value::Object(value.clone()))
        .unwrap_or_else(|err| panic!("failed to deserialize options.json: {}\n{:?}", err, value))
}

/// 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,

    /// Determines what type of [Program] the source code is parsed as.
    ///
    /// - `Some(true)`: parsed as a [Program::Module]
    /// - `Some(false)`: parsed as a [Program::Script]
    /// - `None`: parsed as a [Program] (underlying type is auto-detected)
    pub module: Option<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: Pass,
{
    let input = fs::read_to_string(input).unwrap();

    test_fixture_inner(
        syntax,
        Box::new(|tester| Box::new(tr(tester))),
        &input,
        output,
        config,
    );
}

fn test_fixture_inner<'a>(
    syntax: Syntax,
    tr: Box<dyn 'a + FnOnce(&mut Tester) -> Box<dyn 'a + Pass>>,
    input: &str,
    output: &Path,
    config: FixtureTestConfig,
) {
    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_program =
            tester.apply_transform(noop_pass(), "expected.js", syntax, config.module, &expected)?;

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

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

        Ok(expected_src)
    });

    let mut src_map = if config.sourcemap {
        Some(Vec::new())
    } else {
        None
    };

    let mut sourcemap = None;

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

        let tr = tr(tester);

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

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

        eprintln!("----- {} -----", Color::Green.paint("Comments"));
        eprintln!("{:?}", tester.comments);

        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
            .apply(crate::hygiene::hygiene())
            .apply(crate::fixer::fixer(Some(&tester.comments)));

        let actual_src = {
            let module = &actual;
            let comments: &Rc<SingleThreadedComments> = &tester.comments.clone();

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

            to_code_default(tester.cm.clone(), Some(comments), module)
        };

        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 {
        eprintln!("{}", actual_src);

        if let Some(sourcemap) = &sourcemap {
            eprintln!("----- ----- ----- ----- -----");
            eprintln!("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::new();
            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::new();
        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_STANDARD.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
    }
}