qxide 0.7.0

Qxide: a language and Rust library for classical and quantum computers with C-style syntax, compile-time qubit safety like Rust's ownership, and OpenQASM 3 output
Documentation
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
// Multi-file programs: `import`, `public`, cycles, and linearity across module boundaries.
// Files live in memory; assertions use error codes, file names and line:column.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use super::*;

// Package `app` (the entry package) depends on `bell_utils` and `other`.
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()
}

/// (code, file, line, column) of every error, or empty when the program checks.
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();
    // Only correlated outcomes: the Bell pair was prepared by the imported function.
    for line in out.lines().filter(|l| l.starts_with('[')) {
        assert!(
            line.starts_with("[0, 0]") || line.starts_with("[1, 1]"),
            "{out}"
        );
    }
    // Same circuit as the single-file program.
    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);
}
";
    // `helper` is private, so the wildcard does not import it: unknown function.
    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")
    };
    // The note points at the private declaration in the other file, and help suggests `public`.
    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}"));
    // `flip` reaches bell_utils' `helper` (x) and `g` reaches other's `helper` (z).
    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)]
    );
    // Clashes with a local function and between two imports.
    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)]
    );
    // Two wildcards providing `flip`: only the call is ambiguous; an explicit import settles it.
    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![]);
    // Importing the same function twice is harmless.
    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() {
    // main -> app.a -> app.b -> app.a
    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"
    );
    // A library that imports a module which imports the library back.
    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)]);
    // A module importing itself.
    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();
    // `read` takes ownership: using the qubit afterwards is a use after consume.
    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)]);
    // `prepare` only borrows: the caller still has to measure or discard.
    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)]);
    // The same qubit twice into an imported two-qubit function.
    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)]);
    // A dependency that breaks the rules is reported in its own file.
    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)]
    );
    // An imported function that measures cannot run inside an `if` on a measurement result.
    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`"
    );
    // Syntax errors in imported files point into those files.
    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)]);
}