use js_parse::{parse_module, parse_script};
use quickjs_conformance::{Engine, locate_qjsc};
use std::path::PathBuf;
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> TempDir {
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let sequence = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut path = std::env::temp_dir();
path.push(format!(
"quickjs-rs-redecl-{tag}-{}-{sequence}",
std::process::id()
));
std::fs::create_dir_all(&path).expect("create temp dir");
TempDir(path)
}
fn write(&self, name: &str, contents: &str) -> PathBuf {
let path = self.0.join(name);
std::fs::write(&path, contents).expect("write the case");
path
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn reference(qjsc: &Engine, dir: &TempDir, source: &str, module: bool) -> Option<String> {
let name = if module { "case.mjs" } else { "case.js" };
let path = dir.write(name, source);
let out_path = dir.0.join("out.c");
let mut args = vec!["-c", "-o", out_path.to_str().expect("utf-8 path")];
if module {
args.push("-m");
}
args.push(path.to_str().expect("utf-8 path"));
let output = qjsc.output(&args).expect("run the reference");
let text = if output.stderr.is_empty() {
&output.stdout
} else {
&output.stderr
};
text.lines()
.next()
.filter(|line| !line.is_empty())
.map(|line| line.trim_start_matches("SyntaxError: ").to_string())
}
fn ours_with_position(source: &str, module: bool) -> Option<String> {
let result = if module {
parse_module(source).err()
} else {
parse_script(source).err()
};
result.map(|error| {
if error.positionless {
error.message
} else {
format!(
"{}:{}:{}",
error.message, error.span.start.line, error.span.start.column
)
}
})
}
fn reference_with_position(
qjsc: &Engine,
dir: &TempDir,
source: &str,
module: bool,
) -> Option<String> {
let name = if module { "case.mjs" } else { "case.js" };
let path = dir.write(name, source);
let out_path = dir.0.join("out.c");
let mut args = vec!["-c", "-o", out_path.to_str().expect("utf-8 path")];
if module {
args.push("-m");
}
args.push(path.to_str().expect("utf-8 path"));
let output = qjsc.output(&args).expect("run the reference");
let text = if output.stderr.is_empty() {
&output.stdout
} else {
&output.stderr
};
let mut lines = text.lines().filter(|line| !line.trim().is_empty());
let message = lines.next()?.trim_start_matches("SyntaxError: ");
match lines.next().and_then(|line| {
let mut fields = line.rsplitn(3, ':');
let column = fields.next()?;
let line_number = fields.next()?;
Some((line_number.to_string(), column.to_string()))
}) {
Some((line_number, column)) => Some(format!("{message}:{line_number}:{column}")),
None => Some(message.to_string()),
}
}
fn qjsc() -> Option<Engine> {
locate_qjsc().map(|path| Engine::new("reference", path))
}
const REDECLARATIONS: &[&str] = &[
"{ let a; let a; }",
"{ const a = 1; let a; }",
"{ class a{}; let a; }",
"{ let a; class a{} }",
"{ 'use strict'; { class a{}; class a{} } }",
"{ function a(){} let a; }",
"{ let a; function a(){} }",
"{ function a(){} var a; }",
"{ var a; function a(){} }",
"{ function a(){} const a = 1; }",
"'use strict'; { function a(){} var a; }",
"{ function a(){} function a(){} }",
"'use strict'; { function a(){} function a(){} }",
"{ function a(){} function* a(){} }",
"{ async function a(){} function a(){} }",
"{ function* a(){} function* a(){} }",
"function f(){ function a(){} var a; }",
"function f(){ var a; function a(){} }",
"function f(){ let a; function a(){} }",
"function f(){ function a(){} let a; }",
"function f(){ function a(){} function a(){} }",
"function f(){ let a; let a; }",
"function f(){ var a; let a; }",
"function f(){ let a; var a; }",
"function a(){} let a;",
"let a; function a(){}",
"function a(){} var a;",
"var a; function a(){}",
"function f(a){ let a; }",
"function f(a){ const a = 1; }",
"function f(a){ var a; }",
"function f(){ try{}catch(e){ let e; } }",
"function f(){ try{}catch(e){ var e; } }",
"function f(){ try{}catch(e){ function e(){} } }",
"{ let a; { var a; } }",
"{ var a; { let a; } }",
"{ function a(){} { function a(){} } }",
"{ using a = null; let a }",
"{ let a; using a = null }",
"{ using a = null; using a = null }",
"{ var a; using a = null }",
];
#[test]
fn redeclarations_match_the_reference() {
let Some(qjsc) = qjsc() else {
eprintln!("skipping: no reference qjsc found (run scripts/setup-oracle.sh)");
return;
};
let dir = TempDir::new("redecl");
let mut disagreements = Vec::new();
for source in REDECLARATIONS {
for module in [false, true] {
let want = reference_with_position(&qjsc, &dir, source, module);
let got = ours_with_position(source, module);
if want != got {
let context = if module { "module" } else { "script" };
disagreements.push(format!(
" {source:?} ({context})\n reference: {want:?}\n ours: {got:?}"
));
}
}
}
assert!(
disagreements.is_empty(),
"{} of {} checks disagree:\n{}",
disagreements.len(),
REDECLARATIONS.len() * 2,
disagreements.join("\n")
);
}
const DUPLICATE_PARAMETERS: &[(&str, &str)] = &[
("function f(a, a){}", ""),
("'use strict'; function f(a, a){}", "argument"),
("function f(a, a){'use strict';}", "argument"),
("function* f(a, a){}", ""),
("async function f(a, a){}", ""),
("async function* f(a, a){}", ""),
("({m(a, a){}})", "argument"),
("class C { m(a, a){} }", "argument"),
("class C { static m(a, a){} }", "argument"),
("class C { constructor(a, a){} }", "argument"),
("(a, a) => {};", "argument"),
("function f(a, a = 1){}", "parameter"),
("function f(a = 1, a){}", "parameter"),
("(a, a = 1) => 0;", "parameter"),
("({m(a, a = 1){}})", "parameter"),
("function f([a], [a]){}", "parameter"),
("function f(a, [a]){}", "parameter"),
("class C { m(a, [a]){} }", "parameter"),
("([a], [a]) => 0;", "parameter"),
("function f(a, ...a){}", "argument"),
("(a, ...a) => 0;", "argument"),
("function f([a], a, [a]){}", "parameter"),
("function f([a], a, a){}", "argument"),
("function f(a, a, [b]){}", "argument"),
];
fn expected_duplicate_message(kind: &str) -> String {
match kind {
"argument" => "duplicate argument names not allowed in this context".to_string(),
"parameter" => "duplicate parameter names not allowed in this context".to_string(),
other => panic!("unexpected kind {other:?}"),
}
}
#[test]
fn duplicate_parameters_match_the_reference() {
let Some(qjsc) = qjsc() else {
eprintln!("skipping: no reference qjsc found (run scripts/setup-oracle.sh)");
return;
};
let dir = TempDir::new("params");
let mut disagreements = Vec::new();
for (source, kind) in DUPLICATE_PARAMETERS {
let got = ours_with_position(source, false);
let want = reference_with_position(&qjsc, &dir, source, false);
let message = reference(&qjsc, &dir, source, false);
let pinned = if kind.is_empty() {
None
} else {
Some(expected_duplicate_message(kind))
};
if want != got || pinned != message {
disagreements.push(format!(
" {source:?}\n reference: {want:?}\n ours: {got:?}\n \
pinned: {pinned:?}"
));
}
}
assert!(
disagreements.is_empty(),
"{} of {} checks disagree:\n{}",
disagreements.len(),
DUPLICATE_PARAMETERS.len(),
disagreements.join("\n")
);
}
#[test]
fn a_redeclaration_position_is_the_token_after_the_name() {
let parsed = parse_script("{ let a; let a = 1; }").expect_err("a redeclaration");
assert_eq!((parsed.span.start.line, parsed.span.start.column), (1, 16));
}
#[test]
fn a_duplicate_argument_position_is_the_first_token_of_the_body() {
for (source, column) in [
("'use strict'; function f(a, a){}", 32),
("function f(a, ...a){}", 21),
("(a, a) => 0", 11),
("(a, a) => { return 1 }", 13),
("({m(a, a){}})", 11),
("class C { m(a, a){ return 1 } }", 20),
] {
let error = parse_script(source).expect_err(source);
assert_eq!(
(error.span.start.line, error.span.start.column),
(1, column),
"{source}"
);
}
}