use std::collections::HashMap;
use std::path::{Path, PathBuf};
use super::*;
const BELL_LIB: &str = "\
public void prepare(Qubit a, Qubit b) {
h(a);
cx(a, b);
}
public Bit read(consume Qubit q) {
return measure(q);
}
public void flip(Qubit q) {
helper(q);
}
void helper(Qubit q) {
x(q);
}
";
struct Files(HashMap<PathBuf, String>);
impl Files {
fn new(files: &[(&str, &str)]) -> Self {
Self(
files
.iter()
.map(|(p, s)| (PathBuf::from(p), s.to_string()))
.collect(),
)
}
fn read(&self, p: &Path) -> std::io::Result<String> {
self.0
.get(p)
.cloned()
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))
}
}
fn project(entry_module: Option<Vec<String>>) -> Project {
let root = |name: &str, deps: Vec<usize>| PackageRoot {
name: name.into(),
src_dir: PathBuf::from(name).join("src"),
deps,
};
Project {
packages: vec![
root("app", vec![1, 2]),
root("bell_utils", vec![]),
root("other", vec![]),
],
entry_package: 0,
entry_module,
}
}
fn path(p: &str) -> String {
p.split('/').collect::<PathBuf>().display().to_string()
}
fn errs(entry: &str, files: &[(&str, &str)]) -> Vec<(&'static str, String, usize, usize)> {
errs_in(entry, files, None)
}
fn errs_in(
entry: &str,
files: &[(&str, &str)],
entry_module: Option<Vec<String>>,
) -> Vec<(&'static str, String, usize, usize)> {
let files = Files::new(files);
let read = |p: &Path| files.read(p);
let p = project(entry_module.clone());
let input = Input {
name: "main.qx",
src: entry,
project: Some(&p),
read: &read,
};
let (map, result) = front_input(&input, entry_module.is_none());
match result {
Ok(_) => Vec::new(),
Err(e) => e
.iter()
.map(|d| {
let (l, c) = map.line_col(d.span.start);
(
d.code.as_str(),
map.file_name(d.span.start).to_string(),
l,
c,
)
})
.collect(),
}
}
fn run_files(entry: &str, files: &[(&str, &str)], shots: u64) -> Result<String, String> {
let files = Files::new(files);
let read = |p: &Path| files.read(p);
let p = project(None);
let input = Input {
name: "main.qx",
src: entry,
project: Some(&p),
read: &read,
};
run_input(&input, shots, 0).map_err(|Failure(d)| d)
}
fn bell_files() -> Vec<(&'static str, &'static str)> {
vec![("bell_utils/src/lib.qx", BELL_LIB)]
}
#[test]
fn imported_functions_run_like_local_ones() {
let entry = "\
import bell_utils.prepare;
import bell_utils.read;
void main() {
Qubit a = qubit();
Qubit b = qubit();
prepare(a, b);
Bit ma = read(a);
Bit mb = measure(b);
println(\"{}{}\", ma, mb);
}
";
let out = run_files(entry, &bell_files(), 200).unwrap();
for line in out.lines().filter(|l| l.starts_with('[')) {
assert!(
line.starts_with("[0, 0]") || line.starts_with("[1, 1]"),
"{out}"
);
}
let inline = "\
void main() {
Qubit a = qubit();
Qubit b = qubit();
h(a);
cx(a, b);
Bit ma = measure(a);
Bit mb = measure(b);
println(\"{}{}\", ma, mb);
}
";
let files = Files::new(&bell_files());
let read = |p: &Path| files.read(p);
let p = project(None);
let input = Input {
name: "main.qx",
src: entry,
project: Some(&p),
read: &read,
};
assert_eq!(
qasm_input(&input).unwrap_or_else(|Failure(d)| panic!("{d}")),
qasm("t.qx", inline).unwrap_or_else(|Failure(d)| panic!("{d}"))
);
}
#[test]
fn wildcard_imports_bring_in_public_functions_only() {
let entry = "\
import bell_utils.*;
void main() {
Qubit q = qubit();
flip(q);
helper(q);
discard(q);
}
";
assert_eq!(
errs(entry, &bell_files()),
vec![("Q0202", "main.qx".into(), 6, 5)]
);
let ok = entry.replace(" helper(q);\n", "");
assert_eq!(errs(&ok, &bell_files()), vec![]);
}
#[test]
fn private_functions_cannot_be_imported() {
let entry = "import bell_utils.helper;\nvoid main() {}\n";
assert_eq!(
errs(entry, &bell_files()),
vec![("Q0504", "main.qx".into(), 1, 19)]
);
let files = Files::new(&bell_files());
let read = |p: &Path| files.read(p);
let p = project(None);
let input = Input {
name: "main.qx",
src: entry,
project: Some(&p),
read: &read,
};
let Err(Failure(d)) = check_input(&input) else {
panic!("expected Q0504")
};
let lib = path("bell_utils/src/lib.qx");
assert!(
d.contains(&format!("--> {lib}:14:6")) && d.contains("help: "),
"{d}"
);
}
#[test]
fn private_helpers_with_the_same_name_do_not_collide() {
let other =
"public void g(Qubit q) {\n helper(q);\n}\nvoid helper(Qubit q) {\n z(q);\n}\n";
let entry = "\
import bell_utils.flip;
import other.g;
void helper() {}
void main() {
Qubit q = qubit();
flip(q);
g(q);
helper();
discard(q);
}
";
let mut files = bell_files();
files.push(("other/src/lib.qx", other));
let out = run_files(entry, &files, 1).unwrap();
assert_eq!(out, "");
let files = Files::new(&files);
let read = |p: &Path| files.read(p);
let p = project(None);
let input = Input {
name: "main.qx",
src: entry,
project: Some(&p),
read: &read,
};
let qasm = qasm_input(&input).unwrap_or_else(|Failure(d)| panic!("{d}"));
assert!(
qasm.contains("x q[0];") && qasm.contains("z q[0];"),
"{qasm}"
);
}
#[test]
fn import_errors_have_codes() {
let main = |imports: &str| format!("{imports}\nvoid main() {{}}\n");
let files = bell_files();
assert_eq!(
errs(&main("import nope.f;"), &files),
vec![("Q0501", "main.qx".into(), 1, 8)]
);
assert_eq!(
errs(&main("import bell_utils.gates.f;"), &files),
vec![("Q0502", "main.qx".into(), 1, 1)]
);
assert_eq!(
errs(&main("import bell_utils.nothing;"), &files),
vec![("Q0503", "main.qx".into(), 1, 19)]
);
assert_eq!(
errs(&main("import bell_utils;"), &files),
vec![("Q0509", "main.qx".into(), 1, 1)]
);
assert_eq!(
errs("void main() {}\nimport bell_utils.flip;\n", &files),
vec![("Q0510", "main.qx".into(), 2, 1)]
);
assert_eq!(
errs(
"import bell_utils.flip;\nvoid flip(Qubit q) {}\nvoid main() {}\n",
&files
),
vec![("Q0506", "main.qx".into(), 1, 19)]
);
let mut two = bell_files();
two.push((
"other/src/lib.qx",
"public void flip(Qubit q) {\n z(q);\n}\n",
));
assert_eq!(
errs(&main("import bell_utils.flip;\nimport other.flip;"), &two),
vec![("Q0506", "main.qx".into(), 2, 14)]
);
let wild = "import bell_utils.*;\nimport other.*;\nvoid main() {\n Qubit q = qubit();\n flip(q);\n discard(q);\n}\n";
assert_eq!(errs(wild, &two), vec![("Q0507", "main.qx".into(), 5, 5)]);
let settled = wild.replace("import other.*;", "import other.*;\nimport other.flip;");
assert_eq!(errs(&settled, &two), vec![]);
assert_eq!(
errs(
&main("import bell_utils.flip;\nimport bell_utils.flip;"),
&files
),
vec![]
);
}
#[test]
fn imports_need_a_project() {
let src = "import bell_utils.flip;\nvoid main() {}\n";
let (_, r) = front_input(&Input::file("t.qx", src), true);
let codes: Vec<&str> = r.unwrap_err().iter().map(|d| d.code.as_str()).collect();
assert_eq!(codes, ["Q0508"]);
}
#[test]
fn import_cycles_are_rejected() {
let files = [
("app/src/a.qx", "import app.b.g;\npublic void f() {}\n"),
("app/src/b.qx", "import app.a.f;\npublic void g() {}\n"),
];
let e = errs("import app.a.f;\nvoid main() {}\n", &files);
assert_eq!(
e,
vec![("Q0505", path("app/src/b.qx"), 1, 1)],
"the import closing the cycle is reported"
);
let files = [
("app/src/lib.qx", "import app.a.f;\npublic void top() {}\n"),
("app/src/a.qx", "import app.top;\npublic void f() {}\n"),
];
let e = errs_in(files[0].1, &files, Some(Vec::new()));
assert_eq!(e, vec![("Q0505", path("app/src/a.qx"), 1, 1)]);
let files = [("app/src/a.qx", "import app.a.f;\npublic void f() {}\n")];
let e = errs("import app.a.f;\nvoid main() {}\n", &files);
assert_eq!(e, vec![("Q0505", path("app/src/a.qx"), 1, 1)]);
}
#[test]
fn diamond_imports_are_not_cycles() {
let files = [
(
"app/src/a.qx",
"import app.c.h1;\npublic void f(Qubit q) {\n h1(q);\n}\n",
),
(
"app/src/b.qx",
"import app.c.h1;\npublic void g(Qubit q) {\n h1(q);\n}\n",
),
("app/src/c.qx", "public void h1(Qubit q) {\n h(q);\n}\n"),
];
let entry = "import app.a.f;\nimport app.b.g;\nvoid main() {\n Qubit q = qubit();\n f(q);\n g(q);\n discard(q);\n}\n";
assert_eq!(errs(entry, &files), vec![]);
}
#[test]
fn linearity_holds_across_modules() {
let files = bell_files();
let after = "import bell_utils.read;\nvoid main() {\n Qubit q = qubit();\n Bit m = read(q);\n h(q);\n}\n";
assert_eq!(errs(after, &files), vec![("Q0301", "main.qx".into(), 5, 7)]);
let leak = "import bell_utils.prepare;\nvoid main() {\n Qubit a = qubit();\n Qubit b = qubit();\n prepare(a, b);\n discard(a);\n}\n";
assert_eq!(errs(leak, &files), vec![("Q0302", "main.qx".into(), 4, 11)]);
let dup = "import bell_utils.prepare;\nvoid main() {\n Qubit a = qubit();\n prepare(a, a);\n discard(a);\n}\n";
assert_eq!(errs(dup, &files), vec![("Q0303", "main.qx".into(), 4, 16)]);
let bad = [(
"bell_utils/src/lib.qx",
"public void oops(Qubit q) {\n discard(q);\n}\n",
)];
let entry = "import bell_utils.oops;\nvoid main() {\n Qubit q = qubit();\n oops(q);\n discard(q);\n}\n";
assert_eq!(
errs(entry, &bad),
vec![("Q0313", path("bell_utils/src/lib.qx"), 2, 13)]
);
let cond = "import bell_utils.read;\nvoid main() {\n Qubit a = qubit();\n Bit m = measure(a);\n Qubit t = qubit();\n if m {\n Bit r = read(t);\n }\n discard(t);\n}\n";
let e = errs(cond, &files);
assert!(e.iter().any(|x| x.0 == "Q0314"), "{e:?}");
}
#[test]
fn library_modules_need_no_main() {
assert_eq!(
errs_in(BELL_LIB, &[], Some(Vec::new())),
vec![],
"lib.qx checks without `main`"
);
let files = [("bell_utils/src/lib.qx", "public void f( {}\n")];
let e = errs("import bell_utils.f;\nvoid main() {}\n", &files);
assert_eq!(e, vec![("Q0105", path("bell_utils/src/lib.qx"), 1, 16)]);
}