File: flavor.rs

package info (click to toggle)
rust-swc-core 35.0.0~ds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 62,816 kB
  • sloc: javascript: 873; xml: 538; sh: 358; makefile: 35; python: 5
file content (150 lines) | stat: -rw-r--r-- 5,029 bytes parent folder | download
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
use std::{
    path::{Path, PathBuf},
    process::{Command, Stdio},
};

use anyhow::Context;
use serde_json::{Number, Value};
use swc::SwcComments;
use swc_ecma_ast::EsVersion;
use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax};
use swc_estree_ast::flavor::Flavor;
use swc_estree_compat::babelify::Babelify;
use testing::{assert_eq, json::diff_json_value, DebugUsingDisplay, NormalizedOutput};

fn assert_flavor(flavor: Flavor, input: &Path, output_json_path: &Path) {
    testing::run_test(false, |cm, _handler| {
        let fm = cm.load_file(input).unwrap();

        let lexer = Lexer::new(
            Syntax::Es(Default::default()),
            EsVersion::latest(),
            StringInput::from(&*fm),
            None,
        );
        let mut parser = Parser::new_from(lexer);

        let program = parser.parse_program().unwrap();

        let ctx = swc_estree_compat::babelify::Context {
            fm: fm.clone(),
            cm,
            comments: SwcComments::default(),
        };
        let mut actual = flavor.with(|| {
            let program = program.babelify(&ctx).program;
            serde_json::to_value(&program).unwrap()
        });
        let actual_str = serde_json::to_string_pretty(&actual).unwrap();

        println!("----- swc output -----\n{actual_str}");
        let output = {
            let mut cmd = Command::new("node");
            cmd.arg("-e")
                .arg(include_str!("../scripts/test-acorn.js"))
                .arg(&*fm.src)
                .stderr(Stdio::inherit());
            cmd.output().unwrap()
        };

        let expected =
            String::from_utf8(output.stdout).expect("./acorn.js generated non-utf8 output");

        // We don't care about these cases
        if expected.trim().is_empty() {
            return Ok(());
        }

        {
            let mut expected = serde_json::from_str::<Value>(&expected)
                .with_context(|| format!("acorn.js generated invalid json:\n {expected}"))
                .unwrap();

            println!(
                "----- Expected output -----\n{}",
                serde_json::to_string_pretty(&expected).unwrap()
            );

            // We don't try to match fully.
            actual["end"] = Value::Null;
            expected["end"] = Value::Null;

            actual["range"] = Value::Null;
            expected["range"] = Value::Null;

            diff_json_value(&mut actual, &mut expected, &mut |key, value| {
                if let Value::Object(v) = &mut *value {
                    if let Some("FunctionExpression") = v.get("type").and_then(|v| v.as_str()) {
                        v["range"] = Value::Null;
                        v["start"] = Value::Null;
                        v["end"] = Value::Null;
                    }
                }

                match key {
                    "expression" => {
                        // Normalize false to null
                        if let Value::Bool(false) = value {
                            *value = Value::Null
                        }
                    }

                    "raw" => {
                        // Remove `'` and `"` from raw strings.
                        if let Value::String(s) = value {
                            if (s.starts_with('\'') && s.ends_with('\''))
                                || (s.starts_with('"') && s.ends_with('"'))
                            {
                                *s = s[1..s.len() - 1].to_string();
                            } else if s.starts_with('/') {
                                // We don't need raw value of regex at the moment.
                                *value = Value::Null;
                            }
                        }
                    }

                    "value" => {
                        // Normalize numbers
                        if let Value::Number(n) = value {
                            *n = Number::from_f64(n.as_f64().unwrap()).unwrap();
                        }
                    }

                    // We don't try to match fully.
                    "column" | "line" => {
                        if let Value::Number(..) = value {
                            *value = Value::Null;
                        }
                    }

                    _ => {}
                }
            });

            let actual = serde_json::to_string_pretty(&actual).unwrap();
            let expected = serde_json::to_string_pretty(&expected).unwrap();

            assert_eq!(DebugUsingDisplay(&actual), DebugUsingDisplay(&expected));
        }

        NormalizedOutput::from(actual_str)
            .compare_to_file(output_json_path)
            .unwrap();

        Ok(())
    })
    .unwrap();
}

#[testing::fixture("tests/flavor/acorn/**/input.js")]
fn acorn(input: PathBuf) {
    let output = input.parent().unwrap().join("output.json");

    assert_flavor(
        Flavor::Acorn {
            extra_comments: false,
        },
        &input,
        &output,
    );
}