Skip to main content

metatron_qso/quantum/
openqasm.rs

1//! OpenQASM 2.0 and a subset of OpenQASM 3 into [`Program`]s.
2//!
3//! One parser reads both versions; the `OPENQASM` statement selects the
4//! version (a program without it is read as OpenQASM 3, where the header
5//! is optional).
6//!
7//! Supported:
8//!
9//! * declarations `qreg`/`creg` and `qubit`/`bit` (single or arrays),
10//!   several registers, indices and inclusive slices `r[a:b]`;
11//! * `include "qelib1.inc"` / `"stdgates.inc"` (the standard gates are
12//!   built in; other files are errors);
13//! * `gate` definitions with parameters, used by later gates and the
14//!   program; `U`, `CX` and `gphase`;
15//! * the gate modifiers `ctrl @`, `ctrl(n) @`, `negctrl @`, `inv @` and
16//!   `pow(k) @` for integer `k`;
17//! * `measure q -> c`, `c = measure q`, `reset q`, `barrier` (ignored);
18//! * conditions `if (c == v)`, `if (c[i] == v)`, `if (int[n](c) == v)`
19//!   and `!=`, with a statement or a block, and `else`;
20//! * register broadcasting and parameter expressions with `+ − * / ^ **`,
21//!   `sin cos tan exp ln sqrt arcsin arccos arctan`, `pi π tau τ euler ℇ`.
22//!
23//! Not supported (an error names the feature): classical variables and
24//! arithmetic, loops, subroutines, `defcal`/`cal`, timing, `opaque`,
25//! hardware qubits, and non-integer `pow`.
26//!
27//! The semantics follow each version's specification exactly, including
28//! global phases where they matter. In OpenQASM 3 the built-in
29//! `U(θ, φ, λ)` is `e^{iθ/2}` times the standard U3 matrix (QSO's
30//! [`GateKind::U`]); OpenQASM 2's `U` equals that matrix up to a global
31//! phase, which OpenQASM 2 cannot observe. `gphase` and the phases of
32//! `u2`/`u3` become relative phases under `ctrl @`. QSO keeps these phases while expanding gates and drops the
33//! global phase of the whole program, which is unobservable.
34
35use std::collections::HashMap;
36use std::f64::consts::PI;
37
38use super::circuit::Instruction;
39use super::gates::GateKind;
40use super::program::{Condition, Operation, Program, Register};
41use crate::error::{QsoError, Result};
42
43/// Largest number of qubits a program may declare (simulation needs at
44/// most [`MAX_QUBITS`](super::MAX_QUBITS)).
45pub const MAX_PROGRAM_QUBITS: usize = super::program::MAX_PROGRAM_QUBITS;
46/// Largest number of operations a program may expand to.
47pub const MAX_PROGRAM_OPERATIONS: usize = 1 << 22;
48/// Deepest nesting of blocks and gate calls.
49const MAX_DEPTH: usize = 64;
50/// Greatest height of an expression (nesting plus chained operators).
51const MAX_EXPR_DEPTH: usize = 256;
52
53fn err<T>(msg: impl Into<String>) -> Result<T> {
54    Err(QsoError::Parse(msg.into()))
55}
56
57// ---------------------------------------------------------------------------
58// Lexer
59// ---------------------------------------------------------------------------
60
61#[derive(Clone, Debug, PartialEq)]
62enum Tok {
63    Ident(String),
64    Num(f64, Option<u64>), // value; the exact value of an integer literal
65    Str(String),
66    Punct(&'static str),
67}
68
69const PUNCT2: [&str; 14] = [
70    "->", "==", "!=", "<=", ">=", "&&", "||", "**", "<<", ">>", "+=", "-=", "*=", "/=",
71];
72const PUNCT1: [&str; 25] = [
73    ";", ",", "(", ")", "[", "]", "{", "}", "@", "=", "+", "-", "*", "/", "^", ":", "!", "<", ">",
74    "~", "%", "#", "|", "&", ".",
75];
76
77fn lex(src: &str) -> Result<Vec<(Tok, usize)>> {
78    let chars: Vec<char> = src.chars().collect();
79    let mut out = Vec::new();
80    let mut i = 0;
81    let mut line = 1;
82    while i < chars.len() {
83        let c = chars[i];
84        if c == '\n' {
85            line += 1;
86            i += 1;
87            continue;
88        }
89        if c.is_whitespace() {
90            i += 1;
91            continue;
92        }
93        if c == '/' && chars.get(i + 1) == Some(&'/') {
94            while i < chars.len() && chars[i] != '\n' {
95                i += 1;
96            }
97            continue;
98        }
99        if c == '/' && chars.get(i + 1) == Some(&'*') {
100            i += 2;
101            loop {
102                if i + 1 >= chars.len() {
103                    return err(format!("line {line}: unterminated comment"));
104                }
105                if chars[i] == '\n' {
106                    line += 1;
107                }
108                if chars[i] == '*' && chars[i + 1] == '/' {
109                    i += 2;
110                    break;
111                }
112                i += 1;
113            }
114            continue;
115        }
116        if c.is_alphabetic() || c == '_' {
117            let start = i;
118            while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
119                i += 1;
120            }
121            out.push((Tok::Ident(chars[start..i].iter().collect()), line));
122            continue;
123        }
124        if c.is_ascii_digit() || (c == '.' && chars.get(i + 1).is_some_and(|d| d.is_ascii_digit()))
125        {
126            let start = i;
127            let mut integer = true;
128            while i < chars.len() {
129                let d = chars[i];
130                let prev = if i > start { chars[i - 1] } else { ' ' };
131                if d.is_ascii_digit() || d == '_' {
132                    i += 1;
133                } else if d == '.' || d == 'e' || d == 'E' {
134                    integer = false;
135                    i += 1;
136                } else if (d == '+' || d == '-') && (prev == 'e' || prev == 'E') {
137                    i += 1;
138                } else {
139                    break;
140                }
141            }
142            let text: String = chars[start..i].iter().filter(|&&d| d != '_').collect();
143            let v: f64 = text
144                .parse()
145                .map_err(|_| QsoError::Parse(format!("line {line}: invalid number '{text}'")))?;
146            // Integers keep their exact value (f64 rounds above 2⁵³).
147            let exact = if integer {
148                text.parse::<u64>().ok()
149            } else {
150                None
151            };
152            out.push((Tok::Num(v, exact), line));
153            continue;
154        }
155        if c == '"' {
156            let start = i + 1;
157            i += 1;
158            while i < chars.len() && chars[i] != '"' {
159                if chars[i] == '\n' {
160                    return err(format!("line {line}: unterminated string"));
161                }
162                i += 1;
163            }
164            if i >= chars.len() {
165                return err(format!("line {line}: unterminated string"));
166            }
167            out.push((Tok::Str(chars[start..i].iter().collect()), line));
168            i += 1;
169            continue;
170        }
171        if c == '$' {
172            return err(format!(
173                "line {line}: hardware qubits ('$') are not supported"
174            ));
175        }
176        let two: String = chars[i..chars.len().min(i + 2)].iter().collect();
177        if let Some(p) = PUNCT2.iter().find(|&&p| p == two) {
178            out.push((Tok::Punct(p), line));
179            i += 2;
180            continue;
181        }
182        let one = c.to_string();
183        if let Some(p) = PUNCT1.iter().find(|&&p| p == one) {
184            out.push((Tok::Punct(p), line));
185            i += 1;
186            continue;
187        }
188        return err(format!("line {line}: unexpected character '{c}'"));
189    }
190    Ok(out)
191}
192
193// ---------------------------------------------------------------------------
194// Syntax
195// ---------------------------------------------------------------------------
196
197#[derive(Clone, Debug)]
198enum Expr {
199    Num(f64),
200    Var(String),
201    Neg(Box<Expr>),
202    Bin(char, Box<Expr>, Box<Expr>),
203    Call(String, Box<Expr>),
204}
205
206impl Expr {
207    fn eval(&self, env: &HashMap<String, f64>) -> Result<f64> {
208        Ok(match self {
209            Expr::Num(v) => *v,
210            // Gate parameters shadow the constants: `euler` and `tau` are
211            // ordinary names in OpenQASM 2.
212            Expr::Var(name) => match (env.get(name), name.as_str()) {
213                (Some(v), _) => *v,
214                (None, "pi" | "π") => PI,
215                (None, "tau" | "τ") => 2.0 * PI,
216                (None, "euler" | "ℇ") => std::f64::consts::E,
217                _ => return err(format!("unknown identifier '{name}'")),
218            },
219            Expr::Neg(e) => -e.eval(env)?,
220            Expr::Bin(op, a, b) => {
221                let (a, b) = (a.eval(env)?, b.eval(env)?);
222                match op {
223                    '+' => a + b,
224                    '-' => a - b,
225                    '*' => a * b,
226                    '/' => a / b,
227                    _ => a.powf(b),
228                }
229            }
230            Expr::Call(f, a) => {
231                let a = a.eval(env)?;
232                match f.as_str() {
233                    "sin" => a.sin(),
234                    "cos" => a.cos(),
235                    "tan" => a.tan(),
236                    "exp" => a.exp(),
237                    "ln" => a.ln(),
238                    "sqrt" => a.sqrt(),
239                    "arcsin" => a.asin(),
240                    "arccos" => a.acos(),
241                    _ => a.atan(),
242                }
243            }
244        })
245    }
246
247    fn value(&self, env: &HashMap<String, f64>) -> Result<f64> {
248        let v = self.eval(env)?;
249        if !v.is_finite() {
250            return err("expression is not a finite number");
251        }
252        Ok(v)
253    }
254}
255
256#[derive(Clone, Debug)]
257enum Index {
258    One(Expr),
259    Slice(Expr, Option<Expr>, Expr), // start, step, end (inclusive)
260}
261
262#[derive(Clone, Debug)]
263struct Operand {
264    name: String,
265    index: Option<Index>,
266    line: usize,
267}
268
269#[derive(Clone, Debug)]
270enum Modifier {
271    Ctrl(usize, bool), // count, positive
272    Inv,
273    Pow(Expr),
274}
275
276#[derive(Clone, Debug)]
277struct Call {
278    modifiers: Vec<Modifier>,
279    name: String,
280    params: Vec<Expr>,
281    operands: Vec<Operand>,
282    line: usize,
283}
284
285#[derive(Clone, Copy, Debug, PartialEq)]
286enum Cast {
287    /// No cast: the register's unsigned value, or a bit.
288    None,
289    /// `bool(c)`: whether any bit is set.
290    Bool,
291    /// `int[n](c)` / `uint[n](c)`: `signed`, and the width if given.
292    Int(bool, Option<u64>),
293}
294
295#[derive(Clone, Debug)]
296struct Cond {
297    operand: Operand,
298    cast: Cast,
299    equal: bool,
300    value: u64,
301    /// The value was written `true` or `false`.
302    boolean: bool,
303}
304
305#[derive(Clone, Debug)]
306enum Stmt {
307    Version(f64),
308    Include(String),
309    Qubits(String, usize),
310    Bits(String, usize, Option<Operand>), // optional `= measure q`
311    Gate {
312        name: String,
313        params: Vec<String>,
314        qargs: Vec<String>,
315        body: Vec<Call>,
316        line: usize,
317    },
318    Call(Call),
319    Measure(Operand, Option<Operand>),
320    Reset(Operand),
321    Barrier,
322    If(Cond, Vec<Stmt>, Vec<Stmt>),
323}
324
325const UNSUPPORTED: [&str; 28] = [
326    "opaque",
327    "def",
328    "defcal",
329    "cal",
330    "defcalgrammar",
331    "extern",
332    "for",
333    "while",
334    "const",
335    "let",
336    "int",
337    "uint",
338    "float",
339    "angle",
340    "bool",
341    "duration",
342    "stretch",
343    "box",
344    "delay",
345    "input",
346    "output",
347    "return",
348    "break",
349    "continue",
350    "switch",
351    "array",
352    "complex",
353    "end",
354];
355
356struct Parser {
357    toks: Vec<(Tok, usize)>,
358    pos: usize,
359    depth: usize,
360    /// Height of the expression being parsed: nesting plus the length of
361    /// operator chains, which build left-deep trees.
362    expr_depth: usize,
363}
364
365impl Parser {
366    fn line(&self) -> usize {
367        self.toks
368            .get(self.pos)
369            .or(self.toks.last())
370            .map_or(0, |t| t.1)
371    }
372
373    fn peek(&self) -> Option<&Tok> {
374        self.toks.get(self.pos).map(|t| &t.0)
375    }
376
377    fn peek_at(&self, k: usize) -> Option<&Tok> {
378        self.toks.get(self.pos + k).map(|t| &t.0)
379    }
380
381    fn fail<T>(&self, msg: impl std::fmt::Display) -> Result<T> {
382        err(format!("line {}: {msg}", self.line()))
383    }
384
385    fn is(&self, p: &str) -> bool {
386        matches!(self.peek(), Some(Tok::Punct(q)) if *q == p)
387    }
388
389    fn is_ident(&self, name: &str) -> bool {
390        matches!(self.peek(), Some(Tok::Ident(n)) if n == name)
391    }
392
393    fn eat(&mut self, p: &str) -> bool {
394        if self.is(p) {
395            self.pos += 1;
396            true
397        } else {
398            false
399        }
400    }
401
402    fn expect(&mut self, p: &str) -> Result<()> {
403        if self.eat(p) {
404            Ok(())
405        } else {
406            self.fail(format!("expected '{p}'"))
407        }
408    }
409
410    fn ident(&mut self) -> Result<String> {
411        match self.peek() {
412            Some(Tok::Ident(n)) => {
413                let n = n.clone();
414                self.pos += 1;
415                Ok(n)
416            }
417            _ => self.fail("expected a name"),
418        }
419    }
420
421    fn integer(&mut self) -> Result<u64> {
422        match self.peek() {
423            Some(&Tok::Num(_, Some(n))) => {
424                self.pos += 1;
425                Ok(n)
426            }
427            _ => self.fail("expected a non-negative integer"),
428        }
429    }
430
431    fn deeper<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
432        if self.depth >= MAX_DEPTH {
433            return self.fail(format!("nested deeper than {MAX_DEPTH} levels"));
434        }
435        self.depth += 1;
436        let r = f(self);
437        self.depth -= 1;
438        r
439    }
440
441    /// Run `f` one level deeper in an expression. Evaluating, cloning and
442    /// dropping an expression recurse once per level, so the height is
443    /// bounded.
444    fn deeper_expr<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
445        if self.expr_depth >= MAX_EXPR_DEPTH {
446            return self.fail(format!(
447                "expression nested or chained deeper than {MAX_EXPR_DEPTH} levels"
448            ));
449        }
450        self.expr_depth += 1;
451        let r = f(self);
452        self.expr_depth -= 1;
453        r
454    }
455
456    /// A left-associative chain `first (op next)*` with the operators
457    /// `ops`; each operator adds a level.
458    fn chain(
459        &mut self,
460        ops: [&'static str; 2],
461        next: fn(&mut Self) -> Result<Expr>,
462    ) -> Result<Expr> {
463        let start = self.expr_depth;
464        let mut e = next(self)?;
465        let r = loop {
466            let op = if self.eat(ops[0]) {
467                ops[0]
468            } else if self.eat(ops[1]) {
469                ops[1]
470            } else {
471                break Ok(e);
472            };
473            if self.expr_depth >= MAX_EXPR_DEPTH {
474                break self.fail(format!(
475                    "expression nested or chained deeper than {MAX_EXPR_DEPTH} levels"
476                ));
477            }
478            self.expr_depth += 1;
479            let rhs = match next(self) {
480                Ok(x) => x,
481                Err(x) => break Err(x),
482            };
483            let c = op.chars().next().expect("non-empty operator");
484            e = Expr::Bin(c, Box::new(e), Box::new(rhs));
485        };
486        self.expr_depth = start;
487        r
488    }
489
490    // Expressions: sum → product → unary → power → atom.
491    fn expr(&mut self) -> Result<Expr> {
492        self.deeper_expr(|p| p.chain(["+", "-"], Self::product))
493    }
494
495    fn product(&mut self) -> Result<Expr> {
496        self.chain(["*", "/"], Self::unary)
497    }
498
499    fn unary(&mut self) -> Result<Expr> {
500        if self.eat("-") {
501            return Ok(Expr::Neg(Box::new(self.deeper_expr(Self::unary)?)));
502        }
503        if self.eat("+") {
504            return self.deeper_expr(Self::unary);
505        }
506        let base = self.atom()?;
507        if self.eat("^") || self.eat("**") {
508            let exp = self.deeper_expr(Self::unary)?;
509            return Ok(Expr::Bin('^', Box::new(base), Box::new(exp)));
510        }
511        Ok(base)
512    }
513
514    fn atom(&mut self) -> Result<Expr> {
515        match self.peek().cloned() {
516            Some(Tok::Num(v, _)) => {
517                self.pos += 1;
518                Ok(Expr::Num(v))
519            }
520            Some(Tok::Punct("(")) => {
521                self.pos += 1;
522                let e = self.expr()?;
523                self.expect(")")?;
524                Ok(e)
525            }
526            Some(Tok::Ident(name)) => {
527                self.pos += 1;
528                const FUNCS: [&str; 9] = [
529                    "sin", "cos", "tan", "exp", "ln", "sqrt", "arcsin", "arccos", "arctan",
530                ];
531                if FUNCS.contains(&name.as_str()) {
532                    self.expect("(")?;
533                    let a = self.expr()?;
534                    self.expect(")")?;
535                    return Ok(Expr::Call(name, Box::new(a)));
536                }
537                Ok(Expr::Var(name))
538            }
539            _ => self.fail("expected an expression"),
540        }
541    }
542
543    fn expr_list(&mut self) -> Result<Vec<Expr>> {
544        let mut v = Vec::new();
545        self.expect("(")?;
546        if self.eat(")") {
547            return Ok(v);
548        }
549        loop {
550            v.push(self.expr()?);
551            if self.eat(")") {
552                return Ok(v);
553            }
554            self.expect(",")?;
555        }
556    }
557
558    fn operand(&mut self) -> Result<Operand> {
559        let line = self.line();
560        let name = self.ident()?;
561        let index = if self.eat("[") {
562            let a = self.expr()?;
563            let idx = if self.eat(":") {
564                let b = self.expr()?;
565                if self.eat(":") {
566                    let c = self.expr()?;
567                    Index::Slice(a, Some(b), c)
568                } else {
569                    Index::Slice(a, None, b)
570                }
571            } else {
572                Index::One(a)
573            };
574            self.expect("]")?;
575            Some(idx)
576        } else {
577            None
578        };
579        Ok(Operand { name, index, line })
580    }
581
582    fn operands(&mut self) -> Result<Vec<Operand>> {
583        let mut v = Vec::new();
584        if self.is(";") {
585            return Ok(v);
586        }
587        loop {
588            v.push(self.operand()?);
589            if !self.eat(",") {
590                return Ok(v);
591            }
592        }
593    }
594
595    fn call(&mut self) -> Result<Call> {
596        let line = self.line();
597        let mut modifiers = Vec::new();
598        loop {
599            let is_mod = matches!(self.peek(), Some(Tok::Ident(n)) if ["ctrl", "negctrl", "inv", "pow"].contains(&n.as_str()))
600                && (matches!(self.peek_at(1), Some(Tok::Punct("@")))
601                    || matches!(self.peek_at(1), Some(Tok::Punct("("))));
602            if !is_mod {
603                break;
604            }
605            let m = self.ident()?;
606            let modifier = match m.as_str() {
607                "inv" => Modifier::Inv,
608                "pow" => {
609                    self.expect("(")?;
610                    let e = self.expr()?;
611                    self.expect(")")?;
612                    Modifier::Pow(e)
613                }
614                _ => {
615                    let n = if self.eat("(") {
616                        let n = self.integer()?;
617                        self.expect(")")?;
618                        n as usize
619                    } else {
620                        1
621                    };
622                    if n == 0 || n > 64 {
623                        return self.fail("control counts must lie in 1..=64");
624                    }
625                    Modifier::Ctrl(n, m == "ctrl")
626                }
627            };
628            self.expect("@")?;
629            modifiers.push(modifier);
630        }
631        let name = self.ident()?;
632        let params = if self.is("(") {
633            self.expr_list()?
634        } else {
635            Vec::new()
636        };
637        let operands = self.operands()?;
638        Ok(Call {
639            modifiers,
640            name,
641            params,
642            operands,
643            line,
644        })
645    }
646
647    fn block(&mut self, version: u8) -> Result<Vec<Stmt>> {
648        if self.eat("{") {
649            let mut body = Vec::new();
650            while !self.eat("}") {
651                if self.peek().is_none() {
652                    return self.fail("missing '}'");
653                }
654                body.push(self.deeper(|p| p.statement(version))?);
655            }
656            Ok(body)
657        } else {
658            Ok(vec![self.deeper(|p| p.statement(version))?])
659        }
660    }
661
662    fn condition(&mut self) -> Result<Cond> {
663        // Optional cast: int[n](x), uint[n](x), int(x), bool(x).
664        let kind = match self.peek() {
665            Some(Tok::Ident(n)) if ["int", "uint", "bool"].contains(&n.as_str()) => Some(n.clone()),
666            _ => None,
667        };
668        let (operand, cast) = if let Some(kind) = kind {
669            self.pos += 1;
670            let width = if kind != "bool" && self.eat("[") {
671                let w = self.integer()?;
672                self.expect("]")?;
673                Some(w)
674            } else {
675                None
676            };
677            self.expect("(")?;
678            let o = self.operand()?;
679            self.expect(")")?;
680            let cast = if kind == "bool" {
681                Cast::Bool
682            } else {
683                Cast::Int(kind == "int", width)
684            };
685            (o, cast)
686        } else {
687            (self.operand()?, Cast::None)
688        };
689        let (equal, value, boolean) = if self.eat("==") || self.eat("!=") {
690            let equal = matches!(self.toks[self.pos - 1].0, Tok::Punct("=="));
691            let (value, boolean) = self.cond_value()?;
692            (equal, value, boolean)
693        } else {
694            (false, 0, false) // truthy: value != 0
695        };
696        if cast == Cast::Bool && !boolean && (equal || value != 0) {
697            return self.fail("bool(...) compares with true or false");
698        }
699        Ok(Cond {
700            operand,
701            cast,
702            equal,
703            value,
704            boolean,
705        })
706    }
707
708    fn cond_value(&mut self) -> Result<(u64, bool)> {
709        if self.is_ident("true") {
710            self.pos += 1;
711            return Ok((1, true));
712        }
713        if self.is_ident("false") {
714            self.pos += 1;
715            return Ok((0, true));
716        }
717        Ok((self.integer()?, false))
718    }
719
720    fn statement(&mut self, version: u8) -> Result<Stmt> {
721        let line = self.line();
722        let Some(tok) = self.peek().cloned() else {
723            return self.fail("unexpected end of program");
724        };
725        let Tok::Ident(word) = tok else {
726            return self.fail("expected a statement");
727        };
728        // OpenQASM 3's keywords are ordinary names in OpenQASM 2 (a gate
729        // may be called `box`); `opaque` is OpenQASM 2's own.
730        if (version == 3 && UNSUPPORTED.contains(&word.as_str())) || word == "opaque" {
731            return self.fail(format!("OpenQASM feature '{word}' is not supported"));
732        }
733        match word.as_str() {
734            "OPENQASM" => {
735                self.pos += 1;
736                let v = match self.peek().cloned() {
737                    Some(Tok::Num(v, _)) => {
738                        self.pos += 1;
739                        v
740                    }
741                    _ => return self.fail("expected a version number"),
742                };
743                self.expect(";")?;
744                Ok(Stmt::Version(v))
745            }
746            "include" => {
747                self.pos += 1;
748                let Some(Tok::Str(file)) = self.peek().cloned() else {
749                    return self.fail("expected a file name");
750                };
751                self.pos += 1;
752                self.expect(";")?;
753                Ok(Stmt::Include(file))
754            }
755            "qreg" | "creg" => {
756                self.pos += 1;
757                let name = self.ident()?;
758                self.expect("[")?;
759                let size = self.integer()? as usize;
760                self.expect("]")?;
761                self.expect(";")?;
762                Ok(if word == "qreg" {
763                    Stmt::Qubits(name, size)
764                } else {
765                    Stmt::Bits(name, size, None)
766                })
767            }
768            "qubit" | "bit" => {
769                self.pos += 1;
770                let size = if self.eat("[") {
771                    let s = self.integer()? as usize;
772                    self.expect("]")?;
773                    s
774                } else {
775                    1
776                };
777                let name = self.ident()?;
778                if word == "qubit" {
779                    self.expect(";")?;
780                    return Ok(Stmt::Qubits(name, size));
781                }
782                let init = if self.eat("=") {
783                    if !self.is_ident("measure") {
784                        return self
785                            .fail("classical initialisers other than 'measure' are not supported");
786                    }
787                    self.pos += 1;
788                    Some(self.operand()?)
789                } else {
790                    None
791                };
792                self.expect(";")?;
793                Ok(Stmt::Bits(name, size, init))
794            }
795            "gate" => {
796                self.pos += 1;
797                let name = self.ident()?;
798                let mut params = Vec::new();
799                if self.eat("(") && !self.eat(")") {
800                    loop {
801                        params.push(self.ident()?);
802                        if self.eat(")") {
803                            break;
804                        }
805                        self.expect(",")?;
806                    }
807                }
808                let mut qargs = Vec::new();
809                loop {
810                    qargs.push(self.ident()?);
811                    if !self.eat(",") {
812                        break;
813                    }
814                }
815                self.expect("{")?;
816                let mut body = Vec::new();
817                while !self.eat("}") {
818                    if self.peek().is_none() {
819                        return self.fail("missing '}' in gate definition");
820                    }
821                    if self.is_ident("barrier") {
822                        self.pos += 1;
823                        self.operands()?;
824                        self.expect(";")?;
825                        continue;
826                    }
827                    body.push(self.call()?);
828                    self.expect(";")?;
829                }
830                Ok(Stmt::Gate {
831                    name,
832                    params,
833                    qargs,
834                    body,
835                    line,
836                })
837            }
838            "measure" => {
839                self.pos += 1;
840                let q = self.operand()?;
841                let c = if self.eat("->") {
842                    Some(self.operand()?)
843                } else {
844                    None
845                };
846                self.expect(";")?;
847                Ok(Stmt::Measure(q, c))
848            }
849            "reset" => {
850                self.pos += 1;
851                let q = self.operand()?;
852                self.expect(";")?;
853                Ok(Stmt::Reset(q))
854            }
855            "barrier" => {
856                self.pos += 1;
857                self.operands()?;
858                self.expect(";")?;
859                Ok(Stmt::Barrier)
860            }
861            "if" => {
862                self.pos += 1;
863                self.expect("(")?;
864                let cond = self.condition()?;
865                self.expect(")")?;
866                let then = self.block(version)?;
867                let other = if self.is_ident("else") {
868                    self.pos += 1;
869                    self.block(version)?
870                } else {
871                    Vec::new()
872                };
873                Ok(Stmt::If(cond, then, other))
874            }
875            _ => {
876                // `c = measure q;` or a gate call.
877                let save = self.pos;
878                if !matches!(
879                    self.peek_at(1),
880                    Some(Tok::Punct("(")) | Some(Tok::Punct("@"))
881                ) {
882                    if let Ok(target) = self.operand()
883                        && self.eat("=")
884                    {
885                        if !self.is_ident("measure") {
886                            return self.fail(
887                                "classical assignments other than 'measure' are not supported",
888                            );
889                        }
890                        self.pos += 1;
891                        let q = self.operand()?;
892                        self.expect(";")?;
893                        return Ok(Stmt::Measure(q, Some(target)));
894                    }
895                    self.pos = save;
896                }
897                let call = self.call()?;
898                self.expect(";")?;
899                Ok(Stmt::Call(call))
900            }
901        }
902    }
903}
904
905// ---------------------------------------------------------------------------
906// Lowering
907// ---------------------------------------------------------------------------
908
909/// A gate primitive: an instruction or a (relative, under control) phase.
910#[derive(Clone, Debug)]
911enum Prim {
912    Gate(Instruction),
913    Phase(f64),
914}
915
916struct GateDef {
917    params: Vec<String>,
918    qargs: Vec<String>,
919    body: Vec<Call>,
920}
921
922struct Lower {
923    version: u8,
924    program: Program,
925    gates: HashMap<String, GateDef>,
926    budget: usize,
927}
928
929fn inst(kind: GateKind, targets: &[usize], controls: &[usize], params: &[f64]) -> Prim {
930    Prim::Gate(Instruction {
931        kind,
932        targets: targets.to_vec(),
933        controls: controls.to_vec(),
934        params: params.iter().map(|&v| v.into()).collect(),
935        matrix: None,
936    })
937}
938
939impl Lower {
940    fn spend(&mut self, n: usize) -> Result<()> {
941        if n > self.budget {
942            return err(format!(
943                "the program expands to more than {MAX_PROGRAM_OPERATIONS} operations"
944            ));
945        }
946        self.budget -= n;
947        Ok(())
948    }
949
950    /// The standard gates; `None` if `name` is not one.
951    fn builtin(&self, name: &str, p: &[f64], q: &[usize]) -> Option<Result<Vec<Prim>>> {
952        use GateKind::*;
953        let v3 = self.version == 3;
954        let arity = |nq: usize, np: usize| -> Result<()> {
955            if q.len() != nq || p.len() != np {
956                return err(format!(
957                    "'{name}' expects {nq} qubit(s) and {np} parameter(s), got {} and {}",
958                    q.len(),
959                    p.len()
960                ));
961            }
962            Ok(())
963        };
964        let r = (|| -> Result<Vec<Prim>> {
965            Ok(match name {
966                "U" => {
967                    arity(1, 3)?;
968                    let mut v = vec![inst(U, q, &[], p)];
969                    if v3 {
970                        v.push(Prim::Phase(p[0] / 2.0));
971                    }
972                    v
973                }
974                "CX" => {
975                    arity(2, 0)?;
976                    vec![inst(X, &q[1..], &q[..1], &[])]
977                }
978                "gphase" => {
979                    arity(0, 1)?;
980                    vec![Prim::Phase(p[0])]
981                }
982                "id" => {
983                    // An identity that device rules can give a duration
984                    // (a wait), as `Circuit::id`.
985                    arity(1, 0)?;
986                    let one = C64::new(1.0, 0.0);
987                    let zero = C64::new(0.0, 0.0);
988                    vec![Prim::Gate(Instruction {
989                        kind: Unitary,
990                        targets: q.to_vec(),
991                        controls: Vec::new(),
992                        params: Vec::new(),
993                        matrix: Some(std::sync::Arc::new(vec![one, zero, zero, one])),
994                    })]
995                }
996                "u0" => {
997                    arity(1, 1)?;
998                    vec![]
999                }
1000                "x" | "y" | "z" | "h" | "s" | "sdg" | "t" | "tdg" | "sx" | "sxdg" => {
1001                    arity(1, 0)?;
1002                    let kind = match name {
1003                        "x" => X,
1004                        "y" => Y,
1005                        "z" => Z,
1006                        "h" => H,
1007                        "s" => S,
1008                        "sdg" => Sdg,
1009                        "t" => T,
1010                        "tdg" => Tdg,
1011                        "sx" => SX,
1012                        _ => SXdg,
1013                    };
1014                    vec![inst(kind, q, &[], &[])]
1015                }
1016                "rx" | "ry" | "rz" | "p" | "phase" | "u1" => {
1017                    arity(1, 1)?;
1018                    let kind = match name {
1019                        "rx" => RX,
1020                        "ry" => RY,
1021                        "rz" => RZ,
1022                        _ => P,
1023                    };
1024                    vec![inst(kind, q, &[], p)]
1025                }
1026                "u3" | "u" => {
1027                    arity(1, 3)?;
1028                    let mut v = vec![inst(U, q, &[], p)];
1029                    if v3 && name == "u3" {
1030                        v.push(Prim::Phase(-(p[1] + p[2]) / 2.0));
1031                    }
1032                    v
1033                }
1034                "u2" => {
1035                    arity(1, 2)?;
1036                    let mut v = vec![inst(U, q, &[], &[PI / 2.0, p[0], p[1]])];
1037                    if v3 {
1038                        v.push(Prim::Phase(-(p[0] + p[1]) / 2.0));
1039                    }
1040                    v
1041                }
1042                "cx" | "cy" | "cz" | "ch" => {
1043                    arity(2, 0)?;
1044                    let kind = match name {
1045                        "cy" => Y,
1046                        "cz" => Z,
1047                        "ch" => H,
1048                        _ => X,
1049                    };
1050                    vec![inst(kind, &q[1..], &q[..1], &[])]
1051                }
1052                "cp" | "cphase" | "cu1" | "crx" | "cry" | "crz" => {
1053                    arity(2, 1)?;
1054                    let kind = match name {
1055                        "crx" => RX,
1056                        "cry" => RY,
1057                        "crz" => RZ,
1058                        _ => P,
1059                    };
1060                    vec![inst(kind, &q[1..], &q[..1], p)]
1061                }
1062                "cu3" => {
1063                    arity(2, 3)?;
1064                    vec![inst(U, &q[1..], &q[..1], p)]
1065                }
1066                "cu" => {
1067                    // Controlled e^{iγ}·U3(θ, φ, λ).
1068                    arity(2, 4)?;
1069                    vec![
1070                        inst(P, &q[..1], &[], &p[3..4]),
1071                        inst(U, &q[1..], &q[..1], &p[..3]),
1072                    ]
1073                }
1074                "swap" => {
1075                    arity(2, 0)?;
1076                    vec![inst(Swap, q, &[], &[])]
1077                }
1078                "ccx" => {
1079                    arity(3, 0)?;
1080                    vec![inst(X, &q[2..], &q[..2], &[])]
1081                }
1082                "cswap" => {
1083                    arity(3, 0)?;
1084                    vec![inst(Swap, &q[1..], &q[..1], &[])]
1085                }
1086                "rxx" | "ryy" | "rzz" => {
1087                    arity(2, 1)?;
1088                    let kind = match name {
1089                        "rxx" => RXX,
1090                        "ryy" => RYY,
1091                        _ => RZZ,
1092                    };
1093                    vec![inst(kind, q, &[], p)]
1094                }
1095                _ => return err(String::new()),
1096            })
1097        })();
1098        match r {
1099            Err(QsoError::Parse(m)) if m.is_empty() => None,
1100            other => Some(other),
1101        }
1102    }
1103
1104    fn is_known(&self, name: &str) -> bool {
1105        self.gates.contains_key(name) || self.builtin(name, &[], &[]).is_some()
1106    }
1107
1108    /// Expand a gate with its modifiers on concrete qubits.
1109    fn apply(
1110        &mut self,
1111        call: &Call,
1112        params: &[f64],
1113        qubits: &[usize],
1114        depth: usize,
1115    ) -> Result<Vec<Prim>> {
1116        if depth > MAX_DEPTH {
1117            return err(format!("gate calls nested deeper than {MAX_DEPTH} levels"));
1118        }
1119        let n_ctrl: usize = call
1120            .modifiers
1121            .iter()
1122            .map(|m| if let Modifier::Ctrl(n, _) = m { *n } else { 0 })
1123            .sum();
1124        if qubits.len() < n_ctrl {
1125            return err(format!(
1126                "line {}: '{}' needs {n_ctrl} control qubit(s)",
1127                call.line, call.name
1128            ));
1129        }
1130        let mut seen = qubits.to_vec();
1131        seen.sort_unstable();
1132        if seen.windows(2).any(|w| w[0] == w[1]) {
1133            return err(format!(
1134                "line {}: repeated qubit in '{}'",
1135                call.line, call.name
1136            ));
1137        }
1138        let (controls, base_qubits) = qubits.split_at(n_ctrl);
1139        let mut prims = self.base(&call.name, params, base_qubits, call.line, depth)?;
1140        // Control groups in modifier order; modifiers act innermost first.
1141        let mut groups = Vec::new();
1142        let mut at = 0;
1143        for m in &call.modifiers {
1144            if let Modifier::Ctrl(n, _) = m {
1145                groups.push(&controls[at..at + n]);
1146                at += n;
1147            } else {
1148                groups.push(&controls[..0]);
1149            }
1150        }
1151        for (m, group) in call.modifiers.iter().zip(groups).rev() {
1152            prims = match m {
1153                Modifier::Inv => invert(prims),
1154                Modifier::Pow(e) => {
1155                    let k = e.value(&HashMap::new())?;
1156                    if k.fract() != 0.0 || k.abs() > MAX_PROGRAM_OPERATIONS as f64 {
1157                        return err(format!(
1158                            "line {}: only integer powers are supported, got {k}",
1159                            call.line
1160                        ));
1161                    }
1162                    let base = if k < 0.0 { invert(prims) } else { prims };
1163                    let reps = k.abs() as usize;
1164                    self.spend(weight(&base).saturating_mul(reps).max(1))?;
1165                    let mut out = Vec::with_capacity(base.len() * reps);
1166                    for _ in 0..reps {
1167                        out.extend(base.iter().cloned());
1168                    }
1169                    out
1170                }
1171                Modifier::Ctrl(_, positive) => {
1172                    // Every gate stores the new controls.
1173                    self.spend(prims.len().saturating_mul(group.len()))?;
1174                    let mut out = Vec::with_capacity(prims.len() + 2 * group.len());
1175                    let flips: Vec<Prim> = if *positive {
1176                        Vec::new()
1177                    } else {
1178                        group
1179                            .iter()
1180                            .map(|&c| inst(GateKind::X, &[c], &[], &[]))
1181                            .collect()
1182                    };
1183                    out.extend(flips.iter().cloned());
1184                    for p in prims {
1185                        out.push(match p {
1186                            Prim::Gate(mut i) => {
1187                                i.controls.extend_from_slice(group);
1188                                Prim::Gate(i)
1189                            }
1190                            Prim::Phase(g) => {
1191                                let (last, rest) = group.split_last().expect("non-empty");
1192                                inst(GateKind::P, &[*last], rest, &[g])
1193                            }
1194                        });
1195                    }
1196                    out.extend(flips);
1197                    out
1198                }
1199            };
1200        }
1201        Ok(prims)
1202    }
1203
1204    fn base(
1205        &mut self,
1206        name: &str,
1207        params: &[f64],
1208        qubits: &[usize],
1209        line: usize,
1210        depth: usize,
1211    ) -> Result<Vec<Prim>> {
1212        if let Some(def) = self.gates.get(name) {
1213            if def.params.len() != params.len() || def.qargs.len() != qubits.len() {
1214                return err(format!(
1215                    "line {line}: '{name}' expects {} qubit(s) and {} parameter(s), got {} and {}",
1216                    def.qargs.len(),
1217                    def.params.len(),
1218                    qubits.len(),
1219                    params.len()
1220                ));
1221            }
1222            let env: HashMap<String, f64> = def
1223                .params
1224                .iter()
1225                .cloned()
1226                .zip(params.iter().copied())
1227                .collect();
1228            let map: HashMap<String, usize> = def
1229                .qargs
1230                .iter()
1231                .cloned()
1232                .zip(qubits.iter().copied())
1233                .collect();
1234            let body = def.body.clone();
1235            let mut out = Vec::new();
1236            for c in &body {
1237                let ps = c
1238                    .params
1239                    .iter()
1240                    .map(|e| e.value(&env))
1241                    .collect::<Result<Vec<f64>>>()?;
1242                let qs = c
1243                    .operands
1244                    .iter()
1245                    .map(|o| {
1246                        if o.index.is_some() {
1247                            return err(format!(
1248                                "line {}: gate bodies use whole arguments",
1249                                o.line
1250                            ));
1251                        }
1252                        map.get(&o.name).copied().ok_or_else(|| {
1253                            QsoError::Parse(format!(
1254                                "line {}: unknown argument '{}'",
1255                                o.line, o.name
1256                            ))
1257                        })
1258                    })
1259                    .collect::<Result<Vec<usize>>>()?;
1260                let modifiers = c
1261                    .modifiers
1262                    .iter()
1263                    .map(|m| match m {
1264                        Modifier::Pow(e) => Ok(Modifier::Pow(Expr::Num(e.value(&env)?))),
1265                        other => Ok(other.clone()),
1266                    })
1267                    .collect::<Result<Vec<Modifier>>>()?;
1268                let inner = Call {
1269                    modifiers,
1270                    ..c.clone()
1271                };
1272                let prims = self.apply(&inner, &ps, &qs, depth + 1)?;
1273                // Every call costs, also one that expands to nothing, so
1274                // that doubling definitions of `id` cannot run forever.
1275                self.spend(weight(&prims).max(1))?;
1276                out.extend(prims);
1277            }
1278            return Ok(out);
1279        }
1280        match self.builtin(name, params, qubits) {
1281            Some(r) => r,
1282            None => err(format!("line {line}: unknown gate '{name}'")),
1283        }
1284    }
1285
1286    fn resolve(&self, o: &Operand, quantum: bool) -> Result<Vec<usize>> {
1287        let regs: &[Register] = if quantum {
1288            self.program.qubit_registers()
1289        } else {
1290            self.program.bit_registers()
1291        };
1292        let r = regs.iter().find(|r| r.name == o.name).ok_or_else(|| {
1293            QsoError::Parse(format!(
1294                "line {}: unknown {} register '{}'",
1295                o.line,
1296                if quantum { "quantum" } else { "classical" },
1297                o.name
1298            ))
1299        })?;
1300        let int = |e: &Expr| -> Result<i64> {
1301            let v = e.value(&HashMap::new())?;
1302            if v.fract() != 0.0 || v.abs() > 1e15 {
1303                return err(format!("line {}: indices must be integers", o.line));
1304            }
1305            Ok(v as i64)
1306        };
1307        let check = |i: i64| -> Result<usize> {
1308            // Negative indices count from the end, as in OpenQASM 3.
1309            let k = if i < 0 { r.size as i64 + i } else { i };
1310            if k < 0 || k >= r.size as i64 {
1311                return err(format!(
1312                    "line {}: index {i} out of range for '{}'",
1313                    o.line, o.name
1314                ));
1315            }
1316            Ok(r.offset + k as usize)
1317        };
1318        match &o.index {
1319            None => Ok((r.offset..r.offset + r.size).collect()),
1320            Some(Index::One(e)) => Ok(vec![check(int(e)?)?]),
1321            Some(Index::Slice(a, step, b)) => {
1322                // Negative endpoints count from the end, each on its own.
1323                let from_end = |i: i64| if i < 0 { r.size as i64 + i } else { i };
1324                let (a, b) = (from_end(int(a)?), from_end(int(b)?));
1325                let s = match step {
1326                    Some(e) => int(e)?,
1327                    None => 1,
1328                };
1329                if s == 0 {
1330                    return err(format!("line {}: zero step in slice", o.line));
1331                }
1332                let mut v = Vec::new();
1333                let mut i = a;
1334                while (s > 0 && i <= b) || (s < 0 && i >= b) {
1335                    v.push(check(i)?);
1336                    if v.len() > r.size {
1337                        return err(format!("line {}: slice larger than its register", o.line));
1338                    }
1339                    i += s;
1340                }
1341                Ok(v)
1342            }
1343        }
1344    }
1345
1346    fn lower(&mut self, stmts: &[Stmt], top: bool) -> Result<Vec<Operation>> {
1347        let mut ops = Vec::new();
1348        for s in stmts {
1349            match s {
1350                // The version line, when present, was read before the
1351                // other statements.
1352                Stmt::Version(_) => return err("'OPENQASM' must come first"),
1353                Stmt::Include(f) => {
1354                    if !matches!(f.as_str(), "qelib1.inc" | "stdgates.inc") {
1355                        return err(format!(
1356                            "cannot include '{f}' (only qelib1.inc and stdgates.inc)"
1357                        ));
1358                    }
1359                }
1360                Stmt::Qubits(name, size) => {
1361                    if !top {
1362                        return err("declarations must be at the top level");
1363                    }
1364                    if self.program.n_qubits().saturating_add(*size) > MAX_PROGRAM_QUBITS {
1365                        return err(format!(
1366                            "programs may declare at most {MAX_PROGRAM_QUBITS} qubits"
1367                        ));
1368                    }
1369                    self.program.add_qubit_register(name, *size)?;
1370                }
1371                Stmt::Bits(name, size, init) => {
1372                    if !top {
1373                        return err("declarations must be at the top level");
1374                    }
1375                    self.program.add_bit_register(name, *size)?;
1376                    if let Some(q) = init {
1377                        let target = Operand {
1378                            name: name.clone(),
1379                            index: None,
1380                            line: q.line,
1381                        };
1382                        ops.extend(self.measure(q, &target)?);
1383                    }
1384                }
1385                Stmt::Gate {
1386                    name,
1387                    params,
1388                    qargs,
1389                    body,
1390                    line,
1391                } => {
1392                    if !top {
1393                        return err(format!(
1394                            "line {line}: gates must be defined at the top level"
1395                        ));
1396                    }
1397                    if self.gates.contains_key(name) {
1398                        return err(format!("line {line}: gate '{name}' defined twice"));
1399                    }
1400                    let mut seen = qargs.clone();
1401                    seen.sort();
1402                    seen.dedup();
1403                    if seen.len() != qargs.len() {
1404                        return err(format!("line {line}: repeated argument in gate '{name}'"));
1405                    }
1406                    for c in body {
1407                        if !self.is_known(&c.name) {
1408                            return err(format!(
1409                                "line {}: unknown gate '{}' in the definition of '{name}'",
1410                                c.line, c.name
1411                            ));
1412                        }
1413                    }
1414                    self.gates.insert(
1415                        name.clone(),
1416                        GateDef {
1417                            params: params.clone(),
1418                            qargs: qargs.clone(),
1419                            body: body.clone(),
1420                        },
1421                    );
1422                }
1423                Stmt::Call(call) => {
1424                    let params = call
1425                        .params
1426                        .iter()
1427                        .map(|e| e.value(&HashMap::new()))
1428                        .collect::<Result<Vec<f64>>>()?;
1429                    let lists = call
1430                        .operands
1431                        .iter()
1432                        .map(|o| self.resolve(o, true))
1433                        .collect::<Result<Vec<Vec<usize>>>>()?;
1434                    let width = lists
1435                        .iter()
1436                        .map(Vec::len)
1437                        .filter(|&l| l != 1)
1438                        .max()
1439                        .unwrap_or(1);
1440                    for l in &lists {
1441                        if l.len() != 1 && l.len() != width {
1442                            return err(format!(
1443                                "line {}: registers of different sizes in '{}'",
1444                                call.line, call.name
1445                            ));
1446                        }
1447                    }
1448                    for k in 0..width {
1449                        let qs: Vec<usize> = lists
1450                            .iter()
1451                            .map(|l| if l.len() == 1 { l[0] } else { l[k] })
1452                            .collect();
1453                        let prims = self.apply(call, &params, &qs, 0)?;
1454                        self.spend(weight(&prims).max(1))?;
1455                        for p in prims {
1456                            if let Prim::Gate(i) = p {
1457                                ops.push(Operation::Gate(i));
1458                            }
1459                        }
1460                    }
1461                }
1462                Stmt::Measure(q, c) => {
1463                    let Some(c) = c else {
1464                        return err(format!(
1465                            "line {}: measurements need a classical target",
1466                            q.line
1467                        ));
1468                    };
1469                    ops.extend(self.measure(q, c)?);
1470                }
1471                Stmt::Reset(q) => {
1472                    let qs = self.resolve(q, true)?;
1473                    self.spend(qs.len())?;
1474                    ops.extend(qs.into_iter().map(|qubit| Operation::Reset { qubit }));
1475                }
1476                Stmt::Barrier => {}
1477                Stmt::If(cond, then, other) => {
1478                    let bits = self.resolve(&cond.operand, false)?;
1479                    let line = cond.operand.line;
1480                    if bits.is_empty() || bits.len() > 64 {
1481                        return err(format!("line {line}: conditions read 1 to 64 bits"));
1482                    }
1483                    // `bool(c) == b` is `c != 0` or `c == 0`.
1484                    let (equal, value) = match cond.cast {
1485                        Cast::Bool => (cond.equal != (cond.value == 1), 0),
1486                        _ => (cond.equal, cond.value),
1487                    };
1488                    if let Cast::Int(signed, width) = cond.cast {
1489                        if width.is_some_and(|w| w != bits.len() as u64) {
1490                            return err(format!(
1491                                "line {line}: casting {} bit(s) to an integer of another width",
1492                                bits.len()
1493                            ));
1494                        }
1495                        // A signed value with the top bit set is negative;
1496                        // only non-negative values can be written here.
1497                        if signed && width.is_some() && value >> (bits.len() - 1) != 0 {
1498                            return err(format!(
1499                                "line {line}: {value} is out of range for int[{}]",
1500                                bits.len()
1501                            ));
1502                        }
1503                    }
1504                    if cond.boolean && cond.cast != Cast::Bool && bits.len() != 1 {
1505                        return err(format!(
1506                            "line {line}: only single bits compare with true or false"
1507                        ));
1508                    }
1509                    if bits.len() < 64 && value >> bits.len() != 0 {
1510                        return err(format!(
1511                            "line {line}: {value} does not fit into {} bit(s)",
1512                            bits.len()
1513                        ));
1514                    }
1515                    let then_ops = self.lower(then, false)?;
1516                    let else_ops = self.lower(other, false)?;
1517                    if !else_ops.is_empty() && writes_any(&then_ops, &bits) {
1518                        return err(format!(
1519                            "line {}: an 'if' branch that measures into its own condition cannot have an 'else'",
1520                            cond.operand.line
1521                        ));
1522                    }
1523                    let condition = Condition {
1524                        bits: bits.clone(),
1525                        value,
1526                        equal,
1527                    };
1528                    if !then_ops.is_empty() {
1529                        ops.push(Operation::If {
1530                            condition: condition.clone(),
1531                            body: then_ops,
1532                        });
1533                    }
1534                    if !else_ops.is_empty() {
1535                        ops.push(Operation::If {
1536                            condition: Condition {
1537                                equal: !condition.equal,
1538                                ..condition
1539                            },
1540                            body: else_ops,
1541                        });
1542                    }
1543                }
1544            }
1545        }
1546        Ok(ops)
1547    }
1548
1549    fn measure(&mut self, q: &Operand, c: &Operand) -> Result<Vec<Operation>> {
1550        let qs = self.resolve(q, true)?;
1551        let cs = self.resolve(c, false)?;
1552        if qs.len() != cs.len() {
1553            return err(format!(
1554                "line {}: measuring {} qubit(s) into {} bit(s)",
1555                q.line,
1556                qs.len(),
1557                cs.len()
1558            ));
1559        }
1560        self.spend(qs.len())?;
1561        Ok(qs
1562            .into_iter()
1563            .zip(cs)
1564            .map(|(qubit, bit)| Operation::Measure { qubit, bit })
1565            .collect())
1566    }
1567}
1568
1569fn writes_any(ops: &[Operation], bits: &[usize]) -> bool {
1570    ops.iter().any(|o| match o {
1571        Operation::Measure { bit, .. } => bits.contains(bit),
1572        Operation::If { body, .. } => writes_any(body, bits),
1573        _ => false,
1574    })
1575}
1576
1577/// Size of gate primitives for the operation budget: one per gate and
1578/// one per control qubit it stores.
1579fn weight(prims: &[Prim]) -> usize {
1580    prims
1581        .iter()
1582        .map(|p| match p {
1583            Prim::Gate(i) => 1 + i.controls.len(),
1584            Prim::Phase(_) => 1,
1585        })
1586        .sum()
1587}
1588
1589fn invert(prims: Vec<Prim>) -> Vec<Prim> {
1590    prims
1591        .into_iter()
1592        .rev()
1593        .map(|p| match p {
1594            Prim::Gate(i) => Prim::Gate(i.inverse()),
1595            Prim::Phase(g) => Prim::Phase(-g),
1596        })
1597        .collect()
1598}
1599
1600/// Parse an OpenQASM 2 or 3 program; returns the program and the
1601/// language version (2 or 3).
1602pub fn parse(src: &str) -> Result<(Program, u8)> {
1603    let toks = lex(src)?;
1604    let mut parser = Parser {
1605        toks,
1606        pos: 0,
1607        depth: 0,
1608        expr_depth: 0,
1609    };
1610    // The version decides the meaning of `U`, `u2` and `u3`.
1611    let mut version = 3u8;
1612    if parser.is_ident("OPENQASM") {
1613        let line = parser.line();
1614        if let Stmt::Version(v) = parser.statement(3)? {
1615            version = if v == 2.0 {
1616                2
1617            } else if (3.0..4.0).contains(&v) {
1618                3
1619            } else {
1620                return err(format!("line {line}: unsupported OpenQASM version {v}"));
1621            };
1622        }
1623    }
1624    let mut stmts = Vec::new();
1625    while parser.peek().is_some() {
1626        stmts.push(parser.statement(version)?);
1627    }
1628    let mut lower = Lower {
1629        version,
1630        program: Program::with_registers(Vec::new(), Vec::new())?,
1631        gates: HashMap::new(),
1632        budget: MAX_PROGRAM_OPERATIONS,
1633    };
1634    let ops = lower.lower(&stmts, true)?;
1635    let mut program = lower.program;
1636    for op in ops {
1637        program.push(op)?;
1638    }
1639    Ok((program, version))
1640}
1641
1642impl Program {
1643    /// Parse an OpenQASM 2.0 or OpenQASM 3 program (see
1644    /// [`openqasm`](super::openqasm) for the supported subset).
1645    pub fn from_qasm(src: &str) -> Result<Program> {
1646        parse(src).map(|(p, _)| p)
1647    }
1648}
1649
1650// ---------------------------------------------------------------------------
1651// Export
1652// ---------------------------------------------------------------------------
1653
1654use std::fmt::Write as _;
1655
1656use super::circuit::Circuit;
1657use super::qasm::{emit_instruction, real, zyz};
1658use num_complex::Complex64 as C64;
1659
1660const DEF_RXX: &str = "gate rxx(θ) a, b { h a; h b; cx a, b; rz(θ) b; cx a, b; h a; h b; }";
1661const DEF_RYY: &str =
1662    "gate ryy(θ) a, b { sdg a; h a; sdg b; h b; cx a, b; rz(θ) b; cx a, b; h a; s a; h b; s b; }";
1663const DEF_RZZ: &str = "gate rzz(θ) a, b { cx a, b; rz(θ) b; cx a, b; }";
1664
1665fn uses(ops: &[Operation], kind: GateKind) -> bool {
1666    ops.iter().any(|o| match o {
1667        Operation::Gate(i) => i.kind == kind,
1668        Operation::If { body, .. } => uses(body, kind),
1669        _ => false,
1670    })
1671}
1672
1673/// Words an exported register may not be called: keywords, built-in
1674/// gates and constants of either version.
1675const RESERVED: [&str; 26] = [
1676    "OPENQASM", "include", "qubit", "bit", "qreg", "creg", "gate", "measure", "reset", "barrier",
1677    "if", "else", "ctrl", "negctrl", "inv", "pow", "gphase", "U", "CX", "pi", "tau", "euler",
1678    "true", "false", "opaque", "sizeof",
1679];
1680
1681/// Register names of an export: the program's, made unique and free of
1682/// reserved words by appending `_`.
1683struct Names {
1684    qubits: Vec<String>,
1685    bits: Vec<String>,
1686}
1687
1688impl Program {
1689    /// Names for an export; OpenQASM 2 exports have one quantum register
1690    /// `q`.
1691    fn export_names(&self, version: u8) -> Names {
1692        let mut used = std::collections::HashSet::new();
1693        let mut fresh = |name: &str| {
1694            let mut n = name.to_string();
1695            while RESERVED.contains(&n.as_str())
1696                || UNSUPPORTED.contains(&n.as_str())
1697                || used.contains(&n)
1698            {
1699                n.push('_');
1700            }
1701            used.insert(n.clone());
1702            n
1703        };
1704        let qubits = if version == 2 {
1705            vec![fresh("q")]
1706        } else {
1707            self.qubit_registers()
1708                .iter()
1709                .map(|r| fresh(&r.name))
1710                .collect()
1711        };
1712        let bits = self
1713            .bit_registers()
1714            .iter()
1715            .map(|r| fresh(&r.name))
1716            .collect();
1717        Names { qubits, bits }
1718    }
1719
1720    fn qubit_name(&self, names: &Names, q: usize) -> String {
1721        let (k, r) = self
1722            .qubit_registers()
1723            .iter()
1724            .enumerate()
1725            .find(|(_, r)| q >= r.offset && q < r.offset + r.size)
1726            .expect("qubit in a register");
1727        format!("{}[{}]", names.qubits[k], q - r.offset)
1728    }
1729
1730    fn bit_name(&self, names: &Names, b: usize) -> String {
1731        let (k, r) = self
1732            .bit_registers()
1733            .iter()
1734            .enumerate()
1735            .find(|(_, r)| b >= r.offset && b < r.offset + r.size)
1736            .expect("bit in a register");
1737        format!("{}[{}]", names.bits[k], b - r.offset)
1738    }
1739
1740    /// The index of the register whose bits are exactly `bits`, in order.
1741    fn register_of(&self, bits: &[usize]) -> Option<usize> {
1742        self.bit_registers().iter().position(|r| {
1743            r.size == bits.len() && bits.iter().enumerate().all(|(k, &b)| b == r.offset + k)
1744        })
1745    }
1746
1747    fn gate3(&self, names: &Names, out: &mut String, inst: &Instruction) -> Result<()> {
1748        use GateKind::*;
1749        let a = inst.angles(&[]);
1750        let k = inst.controls.len();
1751        let ctrl = |k: usize| match k {
1752            0 => String::new(),
1753            1 => "ctrl @ ".to_string(),
1754            _ => format!("ctrl({k}) @ "),
1755        };
1756        let args = |p: &[f64]| {
1757            if p.is_empty() {
1758                String::new()
1759            } else {
1760                format!(
1761                    "({})",
1762                    p.iter().map(|&v| real(v)).collect::<Vec<_>>().join(", ")
1763                )
1764            }
1765        };
1766        let qubits: Vec<String> = inst
1767            .controls
1768            .iter()
1769            .chain(&inst.targets)
1770            .map(|&q| self.qubit_name(names, q))
1771            .collect();
1772        let (head, params): (String, Vec<f64>) = match (inst.kind, k) {
1773            (X, 1) => ("cx".into(), vec![]),
1774            (X, 2) => ("ccx".into(), vec![]),
1775            (Y, 1) => ("cy".into(), vec![]),
1776            (Z, 1) => ("cz".into(), vec![]),
1777            (H, 1) => ("ch".into(), vec![]),
1778            (RX, 1) => ("crx".into(), a.clone()),
1779            (RY, 1) => ("cry".into(), a.clone()),
1780            (RZ, 1) => ("crz".into(), a.clone()),
1781            (P, 1) => ("cp".into(), a.clone()),
1782            (Swap, 1) => ("cswap".into(), vec![]),
1783            (H | X | Y | Z | S | Sdg | T | Tdg | SX | Swap, _) => {
1784                let name = match inst.kind {
1785                    SX => "sx".to_string(),
1786                    other => other.name().to_string(),
1787                };
1788                (format!("{}{name}", ctrl(k)), vec![])
1789            }
1790            (SXdg, _) => (format!("{}inv @ sx", ctrl(k)), vec![]),
1791            (RX | RY | RZ | P | RXX | RYY | RZZ, _) => {
1792                (format!("{}{}", ctrl(k), inst.kind.name()), a.clone())
1793            }
1794            (U, 0) => ("U".into(), a.clone()),
1795            (U, _) => (format!("{}cu", ctrl(k - 1)), vec![a[0], a[1], a[2], 0.0]),
1796            (Unitary, 0) if inst.is_identity() => ("id".into(), vec![]),
1797            (Unitary, _) => {
1798                let m = inst.matrix.as_ref().expect("unitary carries a matrix");
1799                if inst.targets.len() != 1 {
1800                    return Err(QsoError::invalid(
1801                        "circuit",
1802                        "custom unitaries on more than one qubit have no OpenQASM representation",
1803                    ));
1804                }
1805                let m: [C64; 4] = [m[0], m[1], m[2], m[3]];
1806                let (theta, phi, lambda, alpha) = zyz(&m);
1807                if k == 0 {
1808                    ("U".into(), vec![theta, phi, lambda])
1809                } else {
1810                    (
1811                        format!("{}cu", ctrl(k - 1)),
1812                        vec![theta, phi, lambda, alpha],
1813                    )
1814                }
1815            }
1816        };
1817        let _ = writeln!(out, "{head}{} {};", args(&params), qubits.join(", "));
1818        Ok(())
1819    }
1820
1821    fn ops3(
1822        &self,
1823        names: &Names,
1824        out: &mut String,
1825        ops: &[Operation],
1826        indent: usize,
1827    ) -> Result<()> {
1828        let pad = "  ".repeat(indent);
1829        for op in ops {
1830            match op {
1831                Operation::Gate(i) => {
1832                    out.push_str(&pad);
1833                    self.gate3(names, out, i)?;
1834                }
1835                Operation::Measure { qubit, bit } => {
1836                    let _ = writeln!(
1837                        out,
1838                        "{pad}{} = measure {};",
1839                        self.bit_name(names, *bit),
1840                        self.qubit_name(names, *qubit)
1841                    );
1842                }
1843                Operation::Reset { qubit } => {
1844                    let _ = writeln!(out, "{pad}reset {};", self.qubit_name(names, *qubit));
1845                }
1846                Operation::If { condition, body } => {
1847                    let lhs = match self.register_of(&condition.bits) {
1848                        Some(k) if condition.bits.len() == 1 => names.bits[k].clone(),
1849                        Some(k) => format!("uint[{}]({})", condition.bits.len(), names.bits[k]),
1850                        None if condition.bits.len() == 1 => {
1851                            self.bit_name(names, condition.bits[0])
1852                        }
1853                        None => {
1854                            return Err(QsoError::invalid(
1855                                "program",
1856                                "conditions must read one bit or a whole register",
1857                            ));
1858                        }
1859                    };
1860                    let op = if condition.equal { "==" } else { "!=" };
1861                    let _ = writeln!(out, "{pad}if ({lhs} {op} {}) {{", condition.value);
1862                    self.ops3(names, out, body, indent + 1)?;
1863                    let _ = writeln!(out, "{pad}}}");
1864                }
1865            }
1866        }
1867        Ok(())
1868    }
1869
1870    /// The program as OpenQASM 3 (standard gates, with `ctrl @` for gates
1871    /// with more controls; `rxx`, `ryy`, `rzz` are defined in the header).
1872    /// Exact including relative phases of controlled gates.
1873    pub fn to_qasm3(&self) -> Result<String> {
1874        let mut out = String::from("OPENQASM 3.0;\ninclude \"stdgates.inc\";\n");
1875        for (kind, def) in [
1876            (GateKind::RXX, DEF_RXX),
1877            (GateKind::RYY, DEF_RYY),
1878            (GateKind::RZZ, DEF_RZZ),
1879        ] {
1880            if uses(self.operations(), kind) {
1881                let _ = writeln!(out, "{def}");
1882            }
1883        }
1884        let names = self.export_names(3);
1885        for (r, name) in self.qubit_registers().iter().zip(&names.qubits) {
1886            let _ = writeln!(out, "qubit[{}] {name};", r.size);
1887        }
1888        for (r, name) in self.bit_registers().iter().zip(&names.bits) {
1889            let _ = writeln!(out, "bit[{}] {name};", r.size);
1890        }
1891        self.ops3(&names, &mut out, self.operations(), 0)?;
1892        Ok(out)
1893    }
1894
1895    /// The program as OpenQASM 2.0: one quantum register `q`, the
1896    /// classical registers of the program (renamed with a trailing `_`
1897    /// where a name is taken or reserved). Conditions must compare a whole
1898    /// register for equality and may not be nested, as OpenQASM 2 requires.
1899    pub fn to_qasm2(&self) -> Result<String> {
1900        let n = self.n_qubits();
1901        let mut out = String::from("OPENQASM 2.0;\ninclude \"qelib1.inc\";\n");
1902        let _ = writeln!(out, "qreg q[{n}];");
1903        let names = self.export_names(2);
1904        for (r, name) in self.bit_registers().iter().zip(&names.bits) {
1905            let _ = writeln!(out, "creg {name}[{}];", r.size);
1906        }
1907        for op in self.operations() {
1908            self.op2(&names, &mut out, op, None)?;
1909        }
1910        Ok(out)
1911    }
1912
1913    fn op2(
1914        &self,
1915        names: &Names,
1916        out: &mut String,
1917        op: &Operation,
1918        guard: Option<&str>,
1919    ) -> Result<()> {
1920        let mut text = String::new();
1921        match op {
1922            Operation::Gate(i) => emit_instruction(&mut text, i, &i.angles(&[]), self.n_qubits())?,
1923            Operation::Measure { qubit, bit } => {
1924                let _ = writeln!(
1925                    text,
1926                    "measure q[{qubit}] -> {};",
1927                    self.bit_name(names, *bit)
1928                );
1929            }
1930            Operation::Reset { qubit } => {
1931                let _ = writeln!(text, "reset q[{qubit}];");
1932            }
1933            Operation::If { condition, body } => {
1934                let reg = self
1935                    .register_of(&condition.bits)
1936                    .filter(|_| condition.equal);
1937                let (Some(reg), None) = (reg, guard) else {
1938                    return Err(QsoError::invalid(
1939                        "program",
1940                        "OpenQASM 2 conditions compare a whole register for equality and do not nest",
1941                    ));
1942                };
1943                // Every statement of the body is guarded separately, which
1944                // is only the same if the body does not change the register.
1945                if body.len() > 1 && writes_any(body, &condition.bits) {
1946                    return Err(QsoError::invalid(
1947                        "program",
1948                        "a conditional block that measures into its own condition has no OpenQASM 2 form",
1949                    ));
1950                }
1951                let g = format!("if({}=={}) ", names.bits[reg], condition.value);
1952                for o in body {
1953                    self.op2(names, out, o, Some(&g))?;
1954                }
1955                return Ok(());
1956            }
1957        }
1958        match guard {
1959            Some(g) => {
1960                for line in text.lines() {
1961                    let _ = writeln!(out, "{g}{line}");
1962                }
1963            }
1964            None => out.push_str(&text),
1965        }
1966        Ok(())
1967    }
1968}
1969
1970/// Export `circuit` (with parameters `theta` bound) as OpenQASM 3; with
1971/// `measure_all` every qubit is measured into the bit of the same index.
1972pub fn to_qasm3(circuit: &Circuit, theta: &[f64], measure_all: bool) -> Result<String> {
1973    Program::from_circuit(circuit, theta, measure_all)?.to_qasm3()
1974}
1975
1976#[cfg(test)]
1977mod tests {
1978    use super::*;
1979    use crate::linalg::CMatrix;
1980    use crate::quantum::StateVector;
1981    use crate::rng::Rng;
1982
1983    fn unitary(c: &Circuit) -> CMatrix {
1984        let n = c.n_qubits();
1985        let mut u = CMatrix::zeros(1 << n, 1 << n);
1986        for col in 0..1 << n {
1987            let mut psi = StateVector::basis(n, col).unwrap();
1988            psi.apply_circuit(c, &[]).unwrap();
1989            for (row, a) in psi.amplitudes().iter().enumerate() {
1990                u[(row, col)] = *a;
1991            }
1992        }
1993        u
1994    }
1995
1996    fn program_unitary(src: &str) -> CMatrix {
1997        unitary(&Program::from_qasm(src).unwrap().to_circuit().unwrap())
1998    }
1999
2000    /// `a` and `b` (bodies on qubits `q[0]`, `q[1]`, …) are the same
2001    /// unitary, phases included.
2002    fn assert_same(a: &str, b: &str, n: usize) {
2003        let head = |v: &str| format!("OPENQASM {v}; include \"stdgates.inc\"; qubit[{n}] q;\n");
2004        let ua = program_unitary(&format!("{}{a}", head("3.0")));
2005        let ub = program_unitary(&format!("{}{b}", head("3.0")));
2006        let diff = (&ua - &ub).iter().map(|z| z.norm()).fold(0.0, f64::max);
2007        assert!(diff < 1e-12, "{a}  vs  {b}: {diff}");
2008    }
2009
2010    #[test]
2011    fn modifiers_and_global_phases_follow_the_specification() {
2012        // U carries e^{iθ/2} in OpenQASM 3: visible under ctrl.
2013        assert_same(
2014            "ctrl @ U(0.3, 0.2, 0.1) q[0], q[1];",
2015            "cu(0.3, 0.2, 0.1, 0.15) q[0], q[1];",
2016            2,
2017        );
2018        // u3 = e^{-i(φ+λ)/2}·U3.
2019        assert_same(
2020            "ctrl @ u3(0.3, 0.2, 0.1) q[0], q[1];",
2021            "cu(0.3, 0.2, 0.1, -0.15) q[0], q[1];",
2022            2,
2023        );
2024        assert_same("ctrl @ gphase(0.7) q[0];", "p(0.7) q[0];", 1);
2025        assert_same(
2026            "ctrl(2) @ gphase(0.7) q[0], q[1];",
2027            "cp(0.7) q[0], q[1];",
2028            2,
2029        );
2030        assert_same(
2031            "negctrl @ x q[0], q[1];",
2032            "x q[0]; cx q[0], q[1]; x q[0];",
2033            2,
2034        );
2035        assert_same("inv @ rx(0.3) q[0];", "rx(-0.3) q[0];", 1);
2036        assert_same("pow(3) @ t q[0];", "t q[0]; t q[0]; t q[0];", 1);
2037        assert_same("pow(-2) @ s q[0];", "sdg q[0]; sdg q[0];", 1);
2038        assert_same("ctrl @ h q[0], q[1];", "ch q[0], q[1];", 2);
2039        assert_same(
2040            "ctrl @ ctrl @ x q[0], q[1], q[2];",
2041            "ccx q[0], q[1], q[2];",
2042            3,
2043        );
2044        assert_same("ctrl @ inv @ s q[1], q[0];", "cp(-pi/2) q[1], q[0];", 2);
2045        // A gate with an internal global phase: e^{it/2}·RZ(t) = P(t).
2046        assert_same(
2047            "gate g(t) a { rz(t) a; gphase(t/2); } ctrl @ g(0.4) q[0], q[1];",
2048            "cp(0.4) q[0], q[1];",
2049            2,
2050        );
2051        // sx = pow(0.5) @ x = e^{iπ/4}·RX(π/2) = U(π/2, −π/2, π/2) in
2052        // OpenQASM 3, exactly.
2053        assert_same(
2054            "ctrl @ sx q[0], q[1];",
2055            "ctrl @ U(pi/2, -pi/2, pi/2) q[0], q[1];",
2056            2,
2057        );
2058        assert_same(
2059            "ctrl @ x q[0], q[1];",
2060            "ctrl @ U(pi, 0, pi) q[0], q[1]; ctrl @ gphase(-pi/2) q[0];",
2061            2,
2062        );
2063        // OpenQASM 2: U has no extra phase (cu3 is controlled U3).
2064        let v2 = program_unitary("OPENQASM 2.0; qreg q[2]; cu3(0.3,0.2,0.1) q[0],q[1];");
2065        let v3 = program_unitary("OPENQASM 3.0; qubit[2] q; cu(0.3, 0.2, 0.1, 0) q[0], q[1];");
2066        assert!((&v2 - &v3).iter().all(|z| z.norm() < 1e-12));
2067    }
2068
2069    fn random_circuit(n: usize, gates: usize, seed: u64) -> Circuit {
2070        use GateKind::*;
2071        let mut rng = Rng::seed_from_u64(seed);
2072        let mut c = Circuit::new(n);
2073        for _ in 0..gates {
2074            let mut qs: Vec<usize> = (0..n).collect();
2075            rng.shuffle(&mut qs);
2076            let k = rng.below(3) as usize; // controls
2077            let a = rng.uniform_range(-3.0, 3.0);
2078            let kinds = [
2079                H, X, Y, Z, S, Sdg, T, Tdg, SX, SXdg, RX, RY, RZ, P, U, Swap, RXX, RYY, RZZ,
2080                Unitary,
2081            ];
2082            let kind = kinds[rng.below(kinds.len() as u64) as usize];
2083            let n_t = kind.num_targets().unwrap_or(1);
2084            if n_t + k > n {
2085                continue;
2086            }
2087            let targets = qs[..n_t].to_vec();
2088            let controls = qs[n_t..n_t + k].to_vec();
2089            let (params, matrix) = match kind {
2090                RX | RY | RZ | P | RXX | RYY | RZZ => (vec![a.into()], None),
2091                U => (vec![a.into(), (a * 0.7).into(), (-a * 0.3).into()], None),
2092                Unitary => {
2093                    let (t, p, l, g) = (a, 0.4 * a, -0.9, 0.3);
2094                    let m = vec![
2095                        C64::from_polar((t / 2.0).cos(), g),
2096                        -C64::from_polar((t / 2.0).sin(), g + l),
2097                        C64::from_polar((t / 2.0).sin(), g + p),
2098                        C64::from_polar((t / 2.0).cos(), g + p + l),
2099                    ];
2100                    (vec![], Some(std::sync::Arc::new(m)))
2101                }
2102                _ => (vec![], None),
2103            };
2104            c.try_push(Instruction {
2105                kind,
2106                targets,
2107                controls,
2108                params,
2109                matrix,
2110            })
2111            .unwrap();
2112        }
2113        c
2114    }
2115
2116    #[test]
2117    fn circuits_round_trip_through_openqasm3_exactly() {
2118        for seed in 0..20 {
2119            let c = random_circuit(4, 30, seed);
2120            let text = to_qasm3(&c, &[], false).unwrap();
2121            let back = Program::from_qasm(&text).unwrap().to_circuit().unwrap();
2122            let (u, v) = (unitary(&c), unitary(&back));
2123            // Equal up to one global phase (uncontrolled U and custom
2124            // unitaries are exported without theirs).
2125            let k = (0..16).find(|&i| u[(i, 0)].norm() > 1e-6).unwrap();
2126            let phase = v[(k, 0)] / u[(k, 0)];
2127            let diff = (&u * phase - &v)
2128                .iter()
2129                .map(|z| z.norm())
2130                .fold(0.0, f64::max);
2131            assert!(diff < 1e-10, "seed {seed}: {diff}\n{text}");
2132            // And through OpenQASM 2 (qelib1 decompositions) where it has
2133            // a form (no controlled rxx, ryy, rzz).
2134            if let Ok(text2) = crate::quantum::to_qasm2(&c, &[], false) {
2135                let back2 = Program::from_qasm(&text2).unwrap().to_circuit().unwrap();
2136                let w = unitary(&back2);
2137                let phase = w[(k, 0)] / u[(k, 0)];
2138                let diff = (&u * phase - &w)
2139                    .iter()
2140                    .map(|z| z.norm())
2141                    .fold(0.0, f64::max);
2142                assert!(diff < 1e-10, "seed {seed} (OpenQASM 2): {diff}");
2143            }
2144        }
2145        // Multi-qubit custom unitaries have no OpenQASM form.
2146        let mut c = Circuit::new(2);
2147        let mut m = vec![C64::new(0.0, 0.0); 16];
2148        for i in 0..4 {
2149            m[i * 5] = C64::new(1.0, 0.0);
2150        }
2151        c.unitary(m, &[0, 1], &[]).unwrap();
2152        assert!(to_qasm3(&c, &[], false).is_err());
2153    }
2154
2155    #[test]
2156    fn dynamic_programs_sample_and_branch() {
2157        // 13 measured coin flips: too many branches for the exact
2158        // distribution, so sampling runs shot by shot.
2159        let mut src = String::from("OPENQASM 3.0; include \"stdgates.inc\"; qubit q; bit[13] c;\n");
2160        for k in 0..13 {
2161            src.push_str(&format!("reset q; h q; c[{k}] = measure q;\n"));
2162        }
2163        let p = Program::from_qasm(&src).unwrap();
2164        assert!(p.probabilities().is_err());
2165        let counts = p.sample(4000, 1).unwrap();
2166        assert_eq!(counts.values().sum::<usize>(), 4000);
2167        let ones: usize = counts.iter().map(|(r, n)| (r & 1) as usize * n).sum();
2168        assert!((ones as f64 / 4000.0 - 0.5).abs() < 0.05);
2169        // Few branches: sampling follows the exact distribution.
2170        let bell = Program::from_qasm(
2171            "OPENQASM 3.0; include \"stdgates.inc\"; qubit[2] q; bit[2] c; h q[0]; cx q[0], q[1]; c = measure q;",
2172        )
2173        .unwrap();
2174        let d = bell.probabilities().unwrap();
2175        assert_eq!(d.keys().copied().collect::<Vec<_>>(), vec![0, 3]);
2176        let s = bell.sample(1000, 2).unwrap();
2177        assert_eq!(s.keys().copied().collect::<Vec<_>>(), vec![0, 3]);
2178        // Measuring a qubit twice, resets and else branches.
2179        let p = Program::from_qasm(
2180            "OPENQASM 3.0; include \"stdgates.inc\"; qubit q; bit[2] c;
2181             x q; c[0] = measure q; reset q; c[1] = measure q;
2182             if (c[0] == 1) { x q; } else { h q; }
2183             c[1] = measure q;",
2184        )
2185        .unwrap();
2186        assert_eq!(
2187            p.probabilities().unwrap().into_iter().collect::<Vec<_>>(),
2188            vec![(3, 1.0)]
2189        );
2190    }
2191
2192    #[test]
2193    fn malformed_and_unsupported_programs_are_errors() {
2194        let head = "OPENQASM 3.0; include \"stdgates.inc\"; qubit[2] q; bit[2] c;\n";
2195        for body in [
2196            "pow(0.5) @ x q[0];",
2197            "gate g a { x a; } gate g a { y a; }",
2198            "gate g a { g a; }",
2199            "gate g a { foo a; }",
2200            "nope q[0];",
2201            "cx q[0];",
2202            "cx q[0], q[0];",
2203            "rx q[0];",
2204            "c[0] = measure q;",
2205            "if (c == 4) x q[0];",
2206            "if (c[0] == 1) { c[0] = measure q[0]; x q[1]; } else { x q[0]; }",
2207            "if (c[0] == 1) { qubit r; }",
2208            "include \"other.inc\";",
2209            "x q[2];",
2210            "x q[0:5];",
2211            "x q[0:0:1];",
2212            "for uint i in [0:1] { x q[i]; }",
2213            "ctrl(0) @ x q[0], q[1];",
2214            "ctrl @ x q[0];",
2215            "c = 3;",
2216            "x q[0]",
2217            "/* unterminated",
2218            "rx(1/0) q[0];",
2219        ] {
2220            assert!(
2221                Program::from_qasm(&format!("{head}{body}")).is_err(),
2222                "{body}"
2223            );
2224        }
2225        assert!(Program::from_qasm("OPENQASM 4.0; qubit q;").is_err());
2226        assert!(Program::from_qasm("OPENQASM 3.0; qubit[100000] q;").is_err());
2227        // Negative indices count from the end; slices are inclusive.
2228        let p = Program::from_qasm(&format!("{head}x q[-1]; h q[0:1];")).unwrap();
2229        assert_eq!(p.len(), 3);
2230        // Exponential gate nesting is cut off by the operation budget.
2231        let mut src = String::from(
2232            "OPENQASM 3.0; include \"stdgates.inc\"; qubit q;\ngate g0 a { x a; x a; }\n",
2233        );
2234        for k in 1..40 {
2235            src.push_str(&format!("gate g{k} a {{ g{} a; g{} a; }}\n", k - 1, k - 1));
2236        }
2237        src.push_str("g39 q;\n");
2238        assert!(Program::from_qasm(&src).is_err());
2239    }
2240
2241    /// Regressions of the review of the OpenQASM reader.
2242    #[test]
2243    fn review_regressions() {
2244        use std::collections::BTreeMap;
2245        let dist = |src: &str| Program::from_qasm(src).unwrap().probabilities().unwrap();
2246        let head = "OPENQASM 3.0; include \"stdgates.inc\";";
2247        // Long operator chains are errors, not stack overflows; moderate
2248        // ones still parse.
2249        let long = vec!["1"; 50_000].join("+");
2250        assert!(Program::from_qasm(&format!("{head} qubit q; rx({long}) q;")).is_err());
2251        let short = vec!["0.01"; 200].join("+");
2252        assert!(Program::from_qasm(&format!("{head} qubit q; rx({short}) q;")).is_ok());
2253        // Gates that expand to nothing still cost: 40 doubling levels of
2254        // `id` hit the budget instead of running for days.
2255        let mut src = String::from("OPENQASM 2.0; include \"qelib1.inc\"; qreg q[1];\n");
2256        src.push_str("gate g0 a { id a; id a; }\n");
2257        for k in 1..40 {
2258            src.push_str(&format!("gate g{k} a {{ g{} a; g{} a; }}\n", k - 1, k - 1));
2259        }
2260        src.push_str("g39 q[0];");
2261        let start = std::time::Instant::now();
2262        assert!(Program::from_qasm(&src).is_err());
2263        assert!(start.elapsed().as_secs_f64() < crate::time_limit(30.0));
2264        // Controls count towards the budget.
2265        let qs: Vec<String> = (0..64).map(|k| format!("q[{k}]")).collect();
2266        let src = format!(
2267            "{head} qubit[64] q; ctrl(63) @ pow(2097000) @ x {};",
2268            qs.join(", ")
2269        );
2270        assert!(Program::from_qasm(&src).is_err());
2271        // bool(c) is c != 0, compared with true or false.
2272        let cond = |c: &str| {
2273            dist(&format!(
2274                "{head} qubit[3] q; bit[3] c; x q[1]; c[0] = measure q[0]; c[1] = measure q[1]; if ({c}) x q[2]; c[2] = measure q[2];"
2275            ))
2276        };
2277        let taken: BTreeMap<u64, f64> = [(0b110, 1.0)].into_iter().collect();
2278        let not_taken: BTreeMap<u64, f64> = [(0b010, 1.0)].into_iter().collect();
2279        assert_eq!(cond("bool(c)"), taken);
2280        assert_eq!(cond("bool(c) == true"), taken);
2281        assert_eq!(cond("bool(c) != false"), taken);
2282        assert_eq!(cond("bool(c) == false"), not_taken);
2283        assert_eq!(cond("c[1] == true"), taken);
2284        assert_eq!(cond("uint[3](c) == 2"), taken);
2285        for bad in [
2286            "bool(c) == 1",
2287            "c == true",
2288            "int[2](c) == 1",
2289            "uint[4](c) == 2",
2290            "int[3](c) == 5",
2291        ] {
2292            assert!(
2293                Program::from_qasm(&format!("{head} qubit q; bit[3] c; if ({bad}) x q;")).is_err(),
2294                "{bad}"
2295            );
2296        }
2297        // Negative slice ends count from the end: q[0:-1] is every qubit.
2298        let all: BTreeMap<u64, f64> = [(0b111, 1.0)].into_iter().collect();
2299        assert_eq!(
2300            dist(&format!(
2301                "{head} qubit[3] q; bit[3] c; x q[0:-1]; c = measure q;"
2302            )),
2303            all
2304        );
2305        // Gate parameters shadow the constants.
2306        let p = dist(
2307            "OPENQASM 2.0; include \"qelib1.inc\"; qreg q[1]; creg c[1]; gate g(euler) a { ry(euler) a; } g(0) q[0]; measure q[0] -> c[0];",
2308        );
2309        assert_eq!(p.into_iter().collect::<Vec<_>>(), vec![(0, 1.0)]);
2310        // Integers above 2⁵³ are exact.
2311        let big = Program::from_qasm(&format!(
2312            "{head} qubit q; bit[63] c; if (uint[63](c) == 9007199254740993) x q;"
2313        ))
2314        .unwrap();
2315        let Operation::If { condition, .. } = &big.operations()[0] else {
2316            panic!("a condition");
2317        };
2318        assert_eq!(condition.value, 9_007_199_254_740_993);
2319        let again = Program::from_qasm(&big.to_qasm3().unwrap()).unwrap();
2320        assert_eq!(again.operations(), big.operations());
2321        // Versions: 2.0 and 3.x only, and only on the first line.
2322        for v in ["2.5", "20", "4", "1.0"] {
2323            assert!(
2324                Program::from_qasm(&format!("OPENQASM {v}; qubit q;")).is_err(),
2325                "{v}"
2326            );
2327        }
2328        assert!(Program::from_qasm("OPENQASM 3.1; qubit q;").is_ok());
2329        assert!(Program::from_qasm("OPENQASM 3.0; qubit q; OPENQASM 2.0;").is_err());
2330        // OpenQASM 3 keywords are names in OpenQASM 2; exports rename
2331        // registers that collide with `q` or with keywords.
2332        let v2 = "OPENQASM 2.0; include \"qelib1.inc\"; gate box a { x a; } qreg a[2]; creg q[1]; creg output[1]; box a[0]; measure a[0] -> q[0]; measure a[1] -> output[0];";
2333        let p = Program::from_qasm(v2).unwrap();
2334        let d = p.probabilities().unwrap();
2335        for text in [p.to_qasm2().unwrap(), p.to_qasm3().unwrap()] {
2336            let back = Program::from_qasm(&text).unwrap_or_else(|e| panic!("{e}\n{text}"));
2337            assert_eq!(back.probabilities().unwrap(), d, "{text}");
2338        }
2339    }
2340}