prism-q 0.35.0

Fast Rust quantum circuit simulator. OpenQASM 3.0, multiple backends, AVX2 SIMD kernels, optional CUDA and MPI, QEC tooling, Python bindings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
//! Tokens to a syntax tree.
//!
//! The grammar is decided here and nowhere else: no later pass rescans text to
//! find where a statement, a block or an argument ended.

use super::ast::{
    Argument, ArrayDecl, ArrayInit, AssignOp, BitResult, Block, CallAssign, CmpOp, Condition,
    Conditional, DefParam, ElementAssign, ForRange, Index, Measure, Modifier, Operand, OperandName,
    Range, RegisterKind, ReturnValue, Stmt, StmtKind, SwitchArm,
};
use super::expr::{self, Expr};
use super::lexer::{Kind, Token};
use super::stream::Stream;
use crate::error::{PrismError, Result};
use smallvec::SmallVec;

/// Keywords that open a classical declaration. `complex` parses and is declined
/// by the evaluator.
const DECLARATION_TYPES: &[&str] = &[
    "int", "uint", "float", "angle", "bool", "complex", "duration", "stretch",
];

/// Keywords the language has and this parser declines, with the text each decline
/// carries. Declining by name returns `UnsupportedConstruct` where the operands
/// would otherwise give a bare syntax error (`while (c[0]) { }` reads as a
/// malformed gate call). A dynamic parse reads the [`LOOP_KEYWORDS`] instead.
const UNSUPPORTED: &[(&str, &str)] = &[
    ("defcal", "defcal"),
    ("extern", "extern"),
    ("opaque", "opaque"),
    ("while", "while"),
    ("break", "break"),
    ("continue", "continue"),
    ("else", "else"),
];

/// The keywords only a dynamic parse reads.
const LOOP_KEYWORDS: &[&str] = &["while", "break", "continue"];

/// Deepest nesting an array initializer may have, which bounds the recursion
/// that reads it.
const MAX_INITIALIZER_DEPTH: usize = 32;

pub(crate) fn parse_program<'a>(tokens: &[Token<'a>]) -> Result<Block<'a>> {
    program(Stream::new(tokens), tokens.len())
}

/// [`parse_program`] with `while`, `break` and `continue`, and conditions and
/// values over the full classical operator set.
pub(crate) fn parse_dynamic_program<'a>(tokens: &[Token<'a>]) -> Result<Block<'a>> {
    program(Stream::dynamic(tokens), tokens.len())
}

fn program<'a>(mut stream: Stream<'_, 'a>, num_tokens: usize) -> Result<Block<'a>> {
    // A gate statement runs six to twelve tokens.
    let mut out = Block::with_capacity(num_tokens / 6);
    while !stream.at_end() {
        out.push(statement(&mut stream)?);
    }
    Ok(out)
}

fn statement<'a>(stream: &mut Stream<'_, 'a>) -> Result<Stmt<'a>> {
    let line = stream.line();
    let kind = statement_kind(stream)?;
    Ok(Stmt { line, kind })
}

fn statement_kind<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    if stream.kind() == Kind::Pragma {
        return Ok(StmtKind::Pragma(stream.advance().text));
    }
    if stream.eat(Kind::Semicolon) {
        return Ok(StmtKind::Empty);
    }
    if stream.kind() != Kind::Ident {
        return Err(stream.expected("a statement"));
    }

    let word = stream.peek().text;
    let reads_loops = stream.is_dynamic() && LOOP_KEYWORDS.contains(&word);
    if let Some((_, construct)) = UNSUPPORTED
        .iter()
        .find(|(keyword, _)| *keyword == word && !reads_loops)
    {
        return Err(PrismError::UnsupportedConstruct {
            construct: (*construct).to_string(),
            line: stream.line(),
        });
    }

    match word {
        "OPENQASM" => version(stream),
        "include" => include(stream),
        "qubit" => oq3_register(stream, RegisterKind::Qubit),
        "bit" => oq3_register(stream, RegisterKind::Classical),
        "qreg" => legacy_register(stream, RegisterKind::Qubit),
        "creg" => legacy_register(stream, RegisterKind::Classical),
        "input" | "output" => port(stream),
        "let" => alias(stream),
        "measure" => measure_arrow(stream),
        "reset" => reset(stream),
        "barrier" => barrier(stream),
        "delay" => delay(stream),
        "if" => conditional(stream),
        "for" => for_loop(stream),
        "while" => while_loop(stream),
        "break" | "continue" => {
            stream.advance();
            stream.expect(Kind::Semicolon)?;
            Ok(if word == "break" {
                StmtKind::Break
            } else {
                StmtKind::Continue
            })
        }
        "switch" => switch(stream),
        "gate" => gate_def(stream),
        "def" => def_def(stream),
        "return" => return_statement(stream),
        "box" => boxed(stream),
        "array" => array_declaration(stream, false),
        "const" => declaration(stream),
        other if DECLARATION_TYPES.contains(&other) => declaration(stream),
        _ => call_or_assignment(stream),
    }
}

fn version<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    let token = stream.peek();
    if !matches!(token.kind, Kind::Int | Kind::Float) {
        return Err(stream.expected("an OpenQASM version"));
    }
    stream.advance();
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::Version(token.text))
}

fn include<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    stream.expect(Kind::Str)?;
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::Include)
}

/// `qubit[4] q;` and `bit c;`, where the size precedes the name.
fn oq3_register<'a>(stream: &mut Stream<'_, 'a>, kind: RegisterKind) -> Result<StmtKind<'a>> {
    stream.advance();
    let size = if stream.eat(Kind::LBracket) {
        let size = expr::parse(stream)?;
        stream.expect(Kind::RBracket)?;
        Some(size)
    } else {
        None
    };
    let name = stream.expect_ident()?;
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::RegisterDecl { kind, name, size })
}

/// `qreg q[4];`, where the size follows the name.
fn legacy_register<'a>(stream: &mut Stream<'_, 'a>, kind: RegisterKind) -> Result<StmtKind<'a>> {
    stream.advance();
    let name = stream.expect_ident()?;
    stream.expect(Kind::LBracket)?;
    let size = expr::parse(stream)?;
    stream.expect(Kind::RBracket)?;
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::RegisterDecl {
        kind,
        name,
        size: Some(size),
    })
}

/// `input float[64] theta;` and `output bit[4] c;`.
fn port<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    let direction = stream.advance().text;
    let (ty, size) = typename(stream)?;
    let name = stream.expect_ident()?;
    stream.expect(Kind::Semicolon)?;
    if direction == "input" {
        return Ok(StmtKind::InputDecl { ty, name });
    }
    Ok(StmtKind::OutputDecl { ty, name, size })
}

/// A type name with its optional width, which every declaration shares.
fn typename<'a>(stream: &mut Stream<'_, 'a>) -> Result<(&'a str, Option<Expr<'a>>)> {
    let ty = stream.expect_ident()?;
    if !stream.eat(Kind::LBracket) {
        return Ok((ty, None));
    }
    let width = expr::parse(stream)?;
    stream.expect(Kind::RBracket)?;
    Ok((ty, Some(width)))
}

fn declaration<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    let constant = stream.eat_keyword("const");
    if stream.is_keyword("array") {
        return array_declaration(stream, constant);
    }
    let (ty, width) = typename(stream)?;
    let name = stream.expect_ident()?;
    let value = if stream.eat(Kind::Assign) {
        Some(expr::parse(stream)?)
    } else {
        None
    };
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::ClassicalDecl {
        constant,
        ty,
        width,
        name,
        value,
    })
}

/// `array[int[32], 2, 3] a = {{1, 2, 3}, {4, 5, 6}};`, the element type first and
/// one size per dimension after it.
fn array_declaration<'a>(stream: &mut Stream<'_, 'a>, constant: bool) -> Result<StmtKind<'a>> {
    stream.advance();
    stream.expect(Kind::LBracket)?;
    let (ty, _width) = typename(stream)?;
    let mut dims = Vec::new();
    while stream.eat(Kind::Comma) {
        dims.push(expr::parse(stream)?);
    }
    if dims.is_empty() {
        return Err(stream.expected("`,` and a size after the element type"));
    }
    stream.expect(Kind::RBracket)?;
    let name = stream.expect_ident()?;
    let init = if stream.eat(Kind::Assign) {
        Some(array_init(stream, 0)?)
    } else {
        None
    };
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::ArrayDecl(Box::new(ArrayDecl {
        constant,
        ty,
        dims,
        name,
        init,
    })))
}

fn array_init<'a>(stream: &mut Stream<'_, 'a>, depth: usize) -> Result<ArrayInit<'a>> {
    if !stream.eat(Kind::LBrace) {
        return Ok(ArrayInit::Value(expr::parse(stream)?));
    }
    if depth >= MAX_INITIALIZER_DEPTH {
        return Err(PrismError::Parse {
            line: stream.line(),
            message: format!("array initializer nests deeper than {MAX_INITIALIZER_DEPTH}"),
        });
    }
    let mut entries = vec![array_init(stream, depth + 1)?];
    while stream.eat(Kind::Comma) {
        entries.push(array_init(stream, depth + 1)?);
    }
    stream.expect(Kind::RBrace)?;
    Ok(ArrayInit::List(entries))
}

/// `let a = q[0:1] ++ q[3];`
fn alias<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    let name = stream.expect_ident()?;
    stream.expect(Kind::Assign)?;
    let mut sources = vec![operand(stream)?];
    while stream.eat(Kind::Concat) {
        sources.push(operand(stream)?);
    }
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::Alias { name, sources })
}

/// `measure q[0] -> c[0];`, the OpenQASM 2 spelling.
fn measure_arrow<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    let source = operand(stream)?;
    if stream.kind() != Kind::Arrow {
        return Err(stream.expected("`->` in `measure qubit -> bit`"));
    }
    stream.advance();
    let target = operand(stream)?;
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::Measure(Box::new(Measure { source, target })))
}

fn reset<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    let targets = operand_list(stream, "reset")?;
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::Reset { targets })
}

fn barrier<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    let targets = if stream.kind() == Kind::Semicolon {
        Vec::new()
    } else {
        operand_list(stream, "barrier")?
    };
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::Barrier { targets })
}

/// `delay[100ns] q[0], q[1];`, where no operand means every qubit.
fn delay<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    stream.expect(Kind::LBracket)?;
    let duration = expr::parse(stream)?;
    stream.expect(Kind::RBracket)?;
    let targets = if stream.kind() == Kind::Semicolon {
        Vec::new()
    } else {
        operand_list(stream, "delay")?
    };
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::Delay { duration, targets })
}

/// `box { ... }`, with an optional duration designator before the body.
fn boxed<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    let duration = if stream.eat(Kind::LBracket) {
        let duration = expr::parse(stream)?;
        stream.expect(Kind::RBracket)?;
        Some(duration)
    } else {
        None
    };
    Ok(StmtKind::Box {
        duration,
        body: braced_block(stream)?,
    })
}

fn operand_list<'a>(stream: &mut Stream<'_, 'a>, what: &str) -> Result<Vec<Operand<'a>>> {
    if stream.kind() == Kind::Semicolon {
        return Err(stream.expected(&format!("a qubit after `{what}`")));
    }
    let mut out = vec![operand(stream)?];
    while stream.eat(Kind::Comma) {
        out.push(operand(stream)?);
    }
    Ok(out)
}

fn operand<'a>(stream: &mut Stream<'_, 'a>) -> Result<Operand<'a>> {
    let token = stream.peek();
    let name = match token.kind {
        Kind::Physical => {
            stream.advance();
            let index = token.text.parse::<usize>().map_err(|_| PrismError::Parse {
                line: token.line as usize,
                message: format!("`${}` is not a qubit index", token.text),
            })?;
            OperandName::Physical(index)
        }
        Kind::Ident => OperandName::Register(stream.advance().text),
        _ => return Err(stream.expected("a qubit or bit reference")),
    };
    let index = if stream.eat(Kind::LBracket) {
        let index = subscript(stream)?;
        stream.expect(Kind::RBracket)?;
        Some(index)
    } else {
        None
    };
    Ok(Operand {
        name,
        index,
        line: token.line as usize,
    })
}

/// What sits between `[` and `]`: one index, an inclusive range with an
/// optional step in the middle, or an explicit set.
fn subscript<'a>(stream: &mut Stream<'_, 'a>) -> Result<Index<'a>> {
    if stream.eat(Kind::LBrace) {
        let mut entries = vec![expr::parse(stream)?];
        while stream.eat(Kind::Comma) {
            entries.push(expr::parse(stream)?);
        }
        stream.expect(Kind::RBrace)?;
        return Ok(Index::Set(entries));
    }

    let first = optional_bound(stream)?;
    if !stream.eat(Kind::Colon) {
        return match first {
            Some(index) => Ok(Index::Single(index)),
            None => Err(stream.expected("an index")),
        };
    }
    let second = optional_bound(stream)?;
    if !stream.eat(Kind::Colon) {
        return Ok(Index::Range(Box::new(Range {
            start: first,
            step: None,
            stop: second,
        })));
    }
    Ok(Index::Range(Box::new(Range {
        start: first,
        step: second,
        stop: optional_bound(stream)?,
    })))
}

/// One end of a range, absent when the source left it open.
fn optional_bound<'a>(stream: &mut Stream<'_, 'a>) -> Result<Option<Expr<'a>>> {
    if matches!(stream.kind(), Kind::Colon | Kind::RBracket) {
        return Ok(None);
    }
    Ok(Some(expr::parse(stream)?))
}

fn conditional<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    let condition = parenthesized_condition(stream)?;
    let then_body = body(stream)?;
    let else_body = if stream.eat_keyword("else") {
        Some(body(stream)?)
    } else {
        None
    };
    Ok(StmtKind::If(Box::new(Conditional {
        condition,
        then_body,
        else_body,
    })))
}

/// `(condition)`. A dynamic parse reads the condition forms a static one does
/// first, and any other expression when none of them spans the parentheses.
fn parenthesized_condition<'a>(stream: &mut Stream<'_, 'a>) -> Result<Condition<'a>> {
    stream.expect(Kind::LParen)?;
    if !stream.is_dynamic() {
        let condition = parse_condition(stream)?;
        stream.expect(Kind::RParen)?;
        return Ok(condition);
    }
    let mark = stream.mark();
    if let Ok(condition) = parse_condition(stream)
        && stream.eat(Kind::RParen)
    {
        return Ok(condition);
    }
    stream.rewind(mark);
    let condition = Condition::Expr(expr::parse(stream)?);
    stream.expect(Kind::RParen)?;
    Ok(condition)
}

fn while_loop<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    let condition = parenthesized_condition(stream)?;
    let body = body(stream)?;
    Ok(StmtKind::While { condition, body })
}

/// A braced block, or the single statement that stands in for one.
fn body<'a>(stream: &mut Stream<'_, 'a>) -> Result<Block<'a>> {
    if stream.kind() == Kind::LBrace {
        return braced_block(stream);
    }
    Ok(vec![statement(stream)?])
}

fn braced_block<'a>(stream: &mut Stream<'_, 'a>) -> Result<Block<'a>> {
    stream.expect(Kind::LBrace)?;
    let mut out = Block::new();
    while !stream.eat(Kind::RBrace) {
        if stream.at_end() {
            return Err(stream.expected("`}` closing a block"));
        }
        out.push(statement(stream)?);
    }
    Ok(out)
}

fn parse_condition<'a>(stream: &mut Stream<'_, 'a>) -> Result<Condition<'a>> {
    if stream.eat(Kind::LParen) {
        let inner = parse_condition(stream)?;
        stream.expect(Kind::RParen)?;
        let Some((op, rhs)) = comparison(stream)? else {
            return Ok(inner);
        };
        // Only a parity reads as a value a comparison can stand against.
        let Condition::Parity {
            bits,
            compare: None,
        } = inner
        else {
            return Err(PrismError::Parse {
                line: stream.line(),
                message: "only a parity condition compares against a literal".into(),
            });
        };
        return Ok(Condition::Parity {
            bits,
            compare: Some((op, rhs)),
        });
    }
    if stream.eat(Kind::Bang) {
        return Ok(Condition::Negated(operand(stream)?));
    }
    let first = operand(stream)?;
    if stream.kind() == Kind::Caret {
        let mut bits = vec![first];
        while stream.eat(Kind::Caret) {
            bits.push(operand(stream)?);
        }
        let compare = comparison(stream)?;
        return Ok(Condition::Parity { bits, compare });
    }
    match comparison(stream)? {
        Some((op, rhs)) => Ok(Condition::Compare {
            lhs: first,
            op,
            rhs,
        }),
        None => Ok(Condition::Truthy(first)),
    }
}

fn comparison<'a>(stream: &mut Stream<'_, 'a>) -> Result<Option<(CmpOp, Expr<'a>)>> {
    let op = match stream.kind() {
        Kind::EqEq => CmpOp::Equal,
        Kind::NotEq => CmpOp::NotEqual,
        _ => return Ok(None),
    };
    stream.advance();
    Ok(Some((op, expr::parse_arithmetic(stream)?)))
}

fn for_loop<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    // `for int i in ...` and `for i in ...` both stand; the type is decoration
    // the loop bounds already carry.
    if stream.kind() == Kind::Ident && matches!(stream.peek().text, "int" | "uint") {
        let mark = stream.mark();
        typename(stream)?;
        if stream.kind() != Kind::Ident {
            stream.rewind(mark);
        }
    }
    let variable = stream.expect_ident()?;
    if !stream.eat_keyword("in") {
        return Err(stream.expected("`in` after a loop variable"));
    }
    let range = for_range(stream)?;
    let body = braced_block(stream)?;
    Ok(StmtKind::For {
        variable,
        range,
        body,
    })
}

fn for_range<'a>(stream: &mut Stream<'_, 'a>) -> Result<ForRange<'a>> {
    if stream.eat(Kind::LBrace) {
        let mut entries = vec![expr::parse(stream)?];
        while stream.eat(Kind::Comma) {
            entries.push(expr::parse(stream)?);
        }
        stream.expect(Kind::RBrace)?;
        return Ok(ForRange::Set(entries));
    }
    if !stream.eat(Kind::LBracket) {
        return Err(PrismError::UnsupportedConstruct {
            construct: format!(
                "for loop range starting with {} (only `[start:stop]`, `[start:step:stop]`, \
                 or `{{a,b,c}}` supported)",
                stream.peek().describe()
            ),
            line: stream.line(),
        });
    }
    let start = expr::parse(stream)?;
    stream.expect(Kind::Colon)?;
    let second = expr::parse(stream)?;
    let (step, stop) = if stream.eat(Kind::Colon) {
        (Some(second), expr::parse(stream)?)
    } else {
        (None, second)
    };
    stream.expect(Kind::RBracket)?;
    Ok(ForRange::Range { start, step, stop })
}

fn switch<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    stream.expect(Kind::LParen)?;
    let operand = operand(stream)?;
    stream.expect(Kind::RParen)?;
    stream.expect(Kind::LBrace)?;
    let mut arms = Vec::new();
    while !stream.eat(Kind::RBrace) {
        let line = stream.line();
        if stream.eat_keyword("case") {
            let mut labels = vec![expr::parse(stream)?];
            while stream.eat(Kind::Comma) {
                labels.push(expr::parse(stream)?);
            }
            arms.push(SwitchArm {
                labels: Some(labels),
                body: braced_block(stream)?,
                line,
            });
        } else if stream.eat_keyword("default") {
            arms.push(SwitchArm {
                labels: None,
                body: braced_block(stream)?,
                line,
            });
        } else {
            return Err(PrismError::Parse {
                line,
                message: format!(
                    "expected `case` or `default` in `switch` body, got {}",
                    stream.peek().describe()
                ),
            });
        }
    }
    Ok(StmtKind::Switch { operand, arms })
}

fn gate_def<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    let name = stream.expect_ident()?;
    let mut params = Vec::new();
    if stream.eat(Kind::LParen) {
        while !stream.eat(Kind::RParen) {
            params.push(stream.expect_ident()?);
            if !stream.eat(Kind::Comma) {
                stream.expect(Kind::RParen)?;
                break;
            }
        }
    }
    let mut qubits = vec![stream.expect_ident()?];
    while stream.eat(Kind::Comma) {
        qubits.push(stream.expect_ident()?);
    }
    let body = braced_block(stream)?;
    Ok(StmtKind::GateDef {
        name,
        params,
        qubits,
        body,
    })
}

fn def_def<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    let line = stream.line();
    stream.advance();
    let name = stream.expect_ident()?;
    stream.expect(Kind::LParen)?;
    let mut args = Vec::new();
    while !stream.eat(Kind::RParen) {
        let (ty, width) = typename(stream)?;
        let arg_name = stream.expect_ident()?;
        args.push(match ty {
            "qubit" => DefParam::Qubit(arg_name),
            "int" | "uint" => DefParam::Value {
                name: arg_name,
                integral: true,
            },
            "float" | "angle" | "complex" => DefParam::Value {
                name: arg_name,
                integral: false,
            },
            "duration" | "stretch" => DefParam::Duration(arg_name),
            "bit" => DefParam::Bit {
                name: arg_name,
                width,
            },
            other => {
                return Err(PrismError::UnsupportedConstruct {
                    construct: format!("def parameter type `{other}`"),
                    line,
                });
            }
        });
        if !stream.eat(Kind::Comma) {
            stream.expect(Kind::RParen)?;
            break;
        }
    }
    let result = if stream.eat(Kind::Arrow) {
        let (ty, width) = typename(stream)?;
        if ty != "bit" {
            return Err(PrismError::UnsupportedConstruct {
                construct: format!(
                    "def `{name}` returning `{ty}`; only a `bit` result has a home in the \
                     instruction list"
                ),
                line,
            });
        }
        Some(BitResult { width })
    } else {
        None
    };
    let body = braced_block(stream)?;
    Ok(StmtKind::DefDef {
        name,
        args,
        result,
        body,
    })
}

fn return_statement<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    stream.advance();
    let value = if stream.kind() == Kind::Semicolon {
        None
    } else if stream.eat_keyword("measure") {
        Some(ReturnValue::Measure(operand(stream)?))
    } else {
        Some(ReturnValue::Value(expr::parse(stream)?))
    };
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::Return(value))
}

/// A gate application, a `def` call, or an assignment, which all open with a
/// name. Only what follows the name tells them apart.
fn call_or_assignment<'a>(stream: &mut Stream<'_, 'a>) -> Result<StmtKind<'a>> {
    // A name followed by an operand, an argument list or `@` opens a call, never
    // an assignment, so the trial parse only runs where one could follow.
    let call_shape = matches!(
        stream.peek_at(1).kind,
        Kind::Ident | Kind::Physical | Kind::LParen | Kind::At
    );
    if !call_shape && let Some(kind) = try_assignment(stream)? {
        return Ok(kind);
    }
    let modifiers = modifier_chain(stream)?;
    let name = stream.expect_ident()?;
    let params = if stream.eat(Kind::LParen) {
        call_arguments(stream)?
    } else {
        SmallVec::new()
    };
    let mut operands = SmallVec::new();
    if stream.kind() != Kind::Semicolon {
        operands.push(operand(stream)?);
        while stream.eat(Kind::Comma) {
            operands.push(operand(stream)?);
        }
    }
    stream.expect(Kind::Semicolon)?;
    Ok(StmtKind::Call {
        modifiers,
        name,
        params,
        operands,
    })
}

/// The entries of a call's parentheses, the opening `(` already read.
fn call_arguments<'a>(stream: &mut Stream<'_, 'a>) -> Result<SmallVec<[Argument<'a>; 1]>> {
    let mut args = SmallVec::new();
    while !stream.eat(Kind::RParen) {
        args.push(argument(stream)?);
        if !stream.eat(Kind::Comma) {
            stream.expect(Kind::RParen)?;
            break;
        }
    }
    Ok(args)
}

/// `c = measure q;`, `n = n + 1;` and `n += 1;`, told from a gate call by the
/// assignment that follows the target.
fn try_assignment<'a>(stream: &mut Stream<'_, 'a>) -> Result<Option<StmtKind<'a>>> {
    let mark = stream.mark();
    let Ok(target) = operand(stream) else {
        stream.rewind(mark);
        return element_assignment(stream);
    };
    let Some(op) = assign_op(stream.kind()) else {
        stream.rewind(mark);
        return element_assignment(stream);
    };
    stream.advance();

    if op.is_none() && stream.eat_keyword("measure") {
        let source = operand(stream)?;
        stream.expect(Kind::Semicolon)?;
        return Ok(Some(StmtKind::Measure(Box::new(Measure {
            source,
            target,
        }))));
    }

    // A call standing alone on the right may hand over qubits and bits, which
    // no expression can hold, so it keeps the call's own argument grammar.
    if op.is_none() && stream.kind() == Kind::Ident && stream.peek_at(1).kind == Kind::LParen {
        let value_mark = stream.mark();
        let name = stream.advance().text;
        stream.advance();
        if let Ok(args) = call_arguments(stream)
            && stream.eat(Kind::Semicolon)
        {
            return Ok(Some(StmtKind::CallAssign(Box::new(CallAssign {
                target,
                name,
                args,
            }))));
        }
        stream.rewind(value_mark);
    }

    let value = expr::parse(stream)?;
    stream.expect(Kind::Semicolon)?;
    if let (Some(array), Some(Index::Single(index))) = (target.register(), &target.index) {
        return Ok(Some(StmtKind::ElementAssign(Box::new(ElementAssign {
            array,
            indices: vec![index.clone()],
            op,
            value,
        }))));
    }
    let Some(name) = target.register().filter(|_| target.index.is_none()) else {
        return Err(PrismError::Parse {
            line: target.line,
            message: format!(
                "`{}` is not a name an assignment can write",
                target.describe()
            ),
        });
    };
    Ok(Some(StmtKind::Assign {
        target: name,
        op,
        value,
    }))
}

/// The assignment an operator token spells: `None` when it is no assignment,
/// `Some(None)` for a plain `=`.
fn assign_op(kind: Kind) -> Option<Option<AssignOp>> {
    match kind {
        Kind::Assign => Some(None),
        Kind::AddAssign => Some(Some(AssignOp::Add)),
        Kind::SubAssign => Some(Some(AssignOp::Sub)),
        Kind::MulAssign => Some(Some(AssignOp::Mul)),
        Kind::DivAssign => Some(Some(AssignOp::Div)),
        Kind::ModAssign => Some(Some(AssignOp::Rem)),
        _ => None,
    }
}

/// `a[0, 2] = 1;` and `a[0][2] += 1;`, the element forms no operand spells.
fn element_assignment<'a>(stream: &mut Stream<'_, 'a>) -> Result<Option<StmtKind<'a>>> {
    if stream.kind() != Kind::Ident || stream.peek_at(1).kind != Kind::LBracket {
        return Ok(None);
    }
    let mark = stream.mark();
    let array = stream.advance().text;
    let indices = expr::index_groups(stream);
    let (Ok(indices), Some(op)) = (indices, assign_op(stream.kind())) else {
        stream.rewind(mark);
        return Ok(None);
    };
    stream.advance();
    let value = expr::parse(stream)?;
    stream.expect(Kind::Semicolon)?;
    Ok(Some(StmtKind::ElementAssign(Box::new(ElementAssign {
        array,
        indices,
        op,
        value,
    }))))
}

/// `inv @`, `pow(k) @`, `ctrl @` and `negctrl @`, in any order and chainable.
fn modifier_chain<'a>(stream: &mut Stream<'_, 'a>) -> Result<Vec<Modifier<'a>>> {
    let mut out = Vec::new();
    loop {
        if stream.kind() != Kind::Ident {
            return Ok(out);
        }
        let word = stream.peek().text;
        if !matches!(word, "inv" | "ctrl" | "negctrl" | "pow") {
            // A name nobody modifies with is still a modifier when `@` follows
            // it, and a gate otherwise.
            if stream.peek_at(1).kind == Kind::At {
                return Err(PrismError::UnsupportedConstruct {
                    construct: word.to_string(),
                    line: stream.line(),
                });
            }
            return Ok(out);
        }
        let mark = stream.mark();
        stream.advance();
        let mut exponent = None;
        if stream.kind() == Kind::LParen {
            stream.advance();
            let parsed = expr::parse(stream);
            match parsed {
                Ok(value) if stream.eat(Kind::RParen) => exponent = Some(value),
                _ => {
                    stream.rewind(mark);
                    return Ok(out);
                }
            }
        }
        if !stream.eat(Kind::At) {
            stream.rewind(mark);
            return Ok(out);
        }
        out.push(match (word, exponent) {
            ("inv", None) => Modifier::Inv,
            ("ctrl", None) => Modifier::Ctrl { negated: false },
            ("negctrl", None) => Modifier::Ctrl { negated: true },
            ("pow", Some(exponent)) => Modifier::Pow(exponent),
            _ => {
                return Err(PrismError::UnsupportedConstruct {
                    construct: word.to_string(),
                    line: stream.line(),
                });
            }
        });
    }
}

/// One entry inside a call's parentheses. A subscripted name standing alone is
/// a qubit or bit reference, or an array element, which only the declaration
/// tells apart; anything else parses as a value, and a bare name is read as
/// whichever the declaration asks for.
fn argument<'a>(stream: &mut Stream<'_, 'a>) -> Result<Argument<'a>> {
    if stream.kind() == Kind::Physical
        || (stream.kind() == Kind::Ident && stream.peek_at(1).kind == Kind::LBracket)
    {
        let mark = stream.mark();
        if let Ok(operand) = operand(stream)
            && matches!(stream.kind(), Kind::Comma | Kind::RParen)
        {
            return Ok(Argument::Operand(operand));
        }
        stream.rewind(mark);
    }
    Ok(Argument::Value(expr::parse(stream)?))
}

/// Parse a comma-separated operand list standing on its own, which is the
/// shape a `#pragma` body writes its targets in.
pub(crate) fn parse_operands<'a>(tokens: &[Token<'a>]) -> Result<Vec<Operand<'a>>> {
    let mut stream = Stream::new(tokens);
    let operands = operand_list(&mut stream, "a qubit reference")?;
    if !stream.at_end() {
        return Err(stream.expected("the end of the qubit list"));
    }
    Ok(operands)
}

#[cfg(test)]
#[path = "parser_tests.rs"]
mod parser_tests;