microsoft/qdk

Public

mirrored from https://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.8.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

compiler/qsc_fir/src/fir.rs

1761lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! The flattened intermediate representation for Q#. FIR is lowered from the HIR.
5//! The blocks, exprs, pats, and stmts from HIR are replaced with IDs that index into
6//! the corresponding lookups in the package. This allows for traversal without
7//! leaking references to the FIR nodes.
8
9#![warn(missing_docs)]
10
11use crate::ty::{Arrow, FunctorSet, FunctorSetValue, GenericArg, GenericParam, Scheme, Ty, Udt};
12use indenter::{indented, Indented};
13use num_bigint::BigInt;
14use qsc_data_structures::{
15 index_map::{IndexMap, Iter},
16 span::Span,
17};
18use std::{
19 cmp::Ordering,
20 fmt::{self, Debug, Display, Formatter, Write},
21 hash::{Hash, Hasher},
22 ops,
23 rc::Rc,
24 result,
25 str::FromStr,
26};
27
28fn set_indentation<'a, 'b>(
29 indent: Indented<'a, Formatter<'b>>,
30 level: usize,
31) -> Indented<'a, Formatter<'b>> {
32 match level {
33 0 => indent.with_str(""),
34 1 => indent.with_str(" "),
35 2 => indent.with_str(" "),
36 _ => unimplemented!("intentation level not supported"),
37 }
38}
39
40/// A unique identifier for an FIR node.
41#[derive(Clone, Copy, Debug)]
42pub struct NodeId(u32);
43
44impl NodeId {
45 /// The ID of the first node.
46 pub const FIRST: Self = Self(0);
47
48 /// The successor of this ID.
49 #[must_use]
50 pub fn successor(self) -> Self {
51 Self(self.0 + 1)
52 }
53}
54
55impl Display for NodeId {
56 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
57 Display::fmt(&self.0, f)
58 }
59}
60
61impl From<NodeId> for usize {
62 fn from(value: NodeId) -> Self {
63 value.0 as usize
64 }
65}
66
67impl From<usize> for NodeId {
68 fn from(value: usize) -> Self {
69 NodeId(
70 value
71 .try_into()
72 .expect("Type Node ID does not fit into u32"),
73 )
74 }
75}
76
77impl From<NodeId> for u32 {
78 fn from(value: NodeId) -> Self {
79 value.0
80 }
81}
82
83impl From<u32> for NodeId {
84 fn from(value: u32) -> Self {
85 NodeId(value)
86 }
87}
88
89impl PartialEq for NodeId {
90 fn eq(&self, other: &Self) -> bool {
91 self.0 == other.0
92 }
93}
94
95impl Eq for NodeId {}
96
97impl PartialOrd for NodeId {
98 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
99 Some(self.cmp(other))
100 }
101}
102
103impl Ord for NodeId {
104 fn cmp(&self, other: &Self) -> Ordering {
105 self.0.cmp(&other.0)
106 }
107}
108
109impl Hash for NodeId {
110 fn hash<H: Hasher>(&self, state: &mut H) {
111 self.0.hash(state);
112 }
113}
114
115macro_rules! fir_id {
116 ($id:ident) => {
117 /// A unique identifier for an FIR node.
118 #[derive(Debug, Clone, Copy)]
119 pub struct $id(pub u32);
120
121 impl $id {
122 /// The successor of this ID.
123 #[must_use]
124 pub fn successor(self) -> Self {
125 Self(self.0 + 1)
126 }
127 }
128
129 impl Default for $id {
130 fn default() -> Self {
131 Self(0)
132 }
133 }
134
135 impl From<NodeId> for $id {
136 fn from(val: NodeId) -> Self {
137 $id(val.into())
138 }
139 }
140
141 impl From<$id> for NodeId {
142 fn from(val: $id) -> Self {
143 NodeId(val.into())
144 }
145 }
146
147 impl From<u32> for $id {
148 fn from(val: u32) -> Self {
149 $id(val)
150 }
151 }
152
153 impl From<$id> for u32 {
154 fn from(id: $id) -> Self {
155 id.0
156 }
157 }
158
159 impl From<$id> for usize {
160 fn from(value: $id) -> Self {
161 value.0 as usize
162 }
163 }
164
165 impl From<usize> for $id {
166 fn from(value: usize) -> Self {
167 $id(value.try_into().expect(&format!(
168 "Value, {}, does not fit into {}",
169 value,
170 stringify!($id)
171 )))
172 }
173 }
174
175 impl PartialEq for $id {
176 fn eq(&self, other: &Self) -> bool {
177 self.0 == other.0
178 }
179 }
180
181 impl Eq for $id {}
182
183 impl PartialOrd for $id {
184 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
185 Some(self.cmp(other))
186 }
187 }
188
189 impl Ord for $id {
190 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
191 self.0.cmp(&other.0)
192 }
193 }
194
195 impl std::hash::Hash for $id {
196 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
197 self.0.hash(state);
198 }
199 }
200
201 impl Display for $id {
202 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
203 Display::fmt(&self.0, f)
204 }
205 }
206 };
207}
208
209fir_id!(BlockId);
210fir_id!(ExprId);
211fir_id!(PatId);
212fir_id!(StmtId);
213fir_id!(LocalVarId);
214
215/// A unique identifier for a package within a package store.
216#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
217pub struct PackageId(usize);
218
219impl PackageId {
220 /// The package ID of the core library.
221 pub const CORE: Self = Self(0);
222
223 /// The successor of this ID.
224 #[must_use]
225 pub fn successor(self) -> Self {
226 Self(self.0 + 1)
227 }
228}
229
230impl Display for PackageId {
231 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
232 Display::fmt(&self.0, f)
233 }
234}
235
236impl From<PackageId> for usize {
237 fn from(value: PackageId) -> Self {
238 value.0
239 }
240}
241
242impl From<usize> for PackageId {
243 fn from(value: usize) -> Self {
244 PackageId(value)
245 }
246}
247
248/// A unique identifier for an item within a package.
249#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
250pub struct LocalItemId(usize);
251
252impl LocalItemId {
253 /// The successor of this ID.
254 #[must_use]
255 pub fn successor(self) -> Self {
256 Self(self.0 + 1)
257 }
258}
259
260impl Display for LocalItemId {
261 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
262 Display::fmt(&self.0, f)
263 }
264}
265
266impl From<usize> for LocalItemId {
267 fn from(value: usize) -> Self {
268 Self(value)
269 }
270}
271
272impl From<LocalItemId> for usize {
273 fn from(value: LocalItemId) -> Self {
274 value.0
275 }
276}
277
278/// A unique identifier for an item within a package store.
279#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
280pub struct ItemId {
281 /// The package ID or `None` for the local package.
282 pub package: Option<PackageId>,
283 /// The item ID.
284 pub item: LocalItemId,
285}
286
287impl Display for ItemId {
288 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
289 match self.package {
290 None => write!(f, "Item {}", self.item),
291 Some(package) => write!(f, "Item {} (Package {package})", self.item),
292 }
293 }
294}
295
296/// A resolution. This connects a usage of a name with the declaration of that name by uniquely
297/// identifying the node that declared it.
298#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
299pub enum Res {
300 /// An invalid resolution.
301 Err,
302 /// A global item.
303 Item(ItemId),
304 /// A local variable.
305 Local(LocalVarId),
306}
307
308impl Display for Res {
309 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
310 match self {
311 Res::Err => f.write_str("Err"),
312 Res::Item(item) => Display::fmt(item, f),
313 Res::Local(node) => write!(f, "Local {node}"),
314 }
315 }
316}
317
318/// A global item.
319pub enum Global<'a> {
320 /// A global callable.
321 Callable(&'a CallableDecl),
322 /// A global user-defined type.
323 Udt,
324}
325
326/// A unique identifier for an item within a package store.
327#[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)]
328pub struct StoreItemId {
329 /// The package ID.
330 pub package: PackageId,
331 /// The item ID.
332 pub item: LocalItemId,
333}
334
335impl Display for StoreItemId {
336 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
337 write!(f, "<item {} in package {}>", self.item, self.package)
338 }
339}
340
341impl From<(PackageId, LocalItemId)> for StoreItemId {
342 fn from(tuple: (PackageId, LocalItemId)) -> Self {
343 Self {
344 package: tuple.0,
345 item: tuple.1,
346 }
347 }
348}
349
350/// A unique identifier for a block within a package store.
351#[derive(Clone, Copy, Debug, PartialEq)]
352pub struct StoreBlockId {
353 /// The package ID.
354 pub package: PackageId,
355 /// The item ID.
356 pub block: BlockId,
357}
358
359impl Display for StoreBlockId {
360 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
361 write!(f, "<block {} in package {}>", self.block, self.package)
362 }
363}
364
365impl From<(PackageId, BlockId)> for StoreBlockId {
366 fn from(tuple: (PackageId, BlockId)) -> Self {
367 Self {
368 package: tuple.0,
369 block: tuple.1,
370 }
371 }
372}
373
374/// A unique identifier for an expression within a package store.
375#[derive(Clone, Copy, Debug, PartialEq)]
376pub struct StoreExprId {
377 /// The package ID.
378 pub package: PackageId,
379 /// The expression ID.
380 pub expr: ExprId,
381}
382
383impl Display for StoreExprId {
384 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
385 write!(f, "<expression {} in package {}>", self.expr, self.package)
386 }
387}
388
389impl From<(PackageId, ExprId)> for StoreExprId {
390 fn from(tuple: (PackageId, ExprId)) -> Self {
391 Self {
392 package: tuple.0,
393 expr: tuple.1,
394 }
395 }
396}
397
398/// A unique identifier for a pattern within a package store.
399#[derive(Clone, Copy, Debug, PartialEq)]
400pub struct StorePatId {
401 /// The package ID.
402 pub package: PackageId,
403 /// The pat ID.
404 pub pat: PatId,
405}
406
407impl Display for StorePatId {
408 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
409 write!(f, "<pattern {} in package {}>", self.pat, self.package)
410 }
411}
412
413impl From<(PackageId, PatId)> for StorePatId {
414 fn from(tuple: (PackageId, PatId)) -> Self {
415 Self {
416 package: tuple.0,
417 pat: tuple.1,
418 }
419 }
420}
421
422/// A unique identifier for a statement within a package store.
423#[derive(Clone, Copy, Debug, PartialEq)]
424pub struct StoreStmtId {
425 /// The package ID.
426 pub package: PackageId,
427 /// The statement ID.
428 pub stmt: StmtId,
429}
430
431impl Display for StoreStmtId {
432 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
433 write!(f, "<pattern {} in package {}>", self.stmt, self.package)
434 }
435}
436
437impl From<(PackageId, StmtId)> for StoreStmtId {
438 fn from(tuple: (PackageId, StmtId)) -> Self {
439 Self {
440 package: tuple.0,
441 stmt: tuple.1,
442 }
443 }
444}
445
446/// A trait to find elements in a package store.
447pub trait PackageStoreLookup {
448 /// Gets a block.
449 fn get_block(&self, id: StoreBlockId) -> &Block;
450 /// Gets an expression.
451 fn get_expr(&self, id: StoreExprId) -> &Expr;
452 /// Gets a global.
453 fn get_global(&self, id: StoreItemId) -> Option<Global>;
454 /// Gets a pat.
455 fn get_pat(&self, id: StorePatId) -> &Pat;
456 /// Gets a statement.
457 fn get_stmt(&self, id: StoreStmtId) -> &Stmt;
458 /// Gets an item.
459 fn get_item(&self, id: StoreItemId) -> &Item;
460}
461
462/// A FIR package store.
463#[derive(Debug, Default)]
464pub struct PackageStore(IndexMap<PackageId, Package>);
465
466impl PackageStoreLookup for PackageStore {
467 fn get_block(&self, id: StoreBlockId) -> &Block {
468 self.get(id.package).get_block(id.block)
469 }
470
471 fn get_expr(&self, id: StoreExprId) -> &Expr {
472 self.get(id.package).get_expr(id.expr)
473 }
474
475 fn get_global(&self, id: StoreItemId) -> Option<Global> {
476 self.get(id.package).get_global(id.item)
477 }
478
479 fn get_pat(&self, id: StorePatId) -> &Pat {
480 self.get(id.package).get_pat(id.pat)
481 }
482
483 fn get_stmt(&self, id: StoreStmtId) -> &Stmt {
484 self.get(id.package).get_stmt(id.stmt)
485 }
486
487 fn get_item(&self, id: StoreItemId) -> &Item {
488 self.get(id.package).get_item(id.item)
489 }
490}
491
492impl PackageStore {
493 /// Gets a package from the store.
494 #[must_use]
495 pub fn get(&self, id: PackageId) -> &Package {
496 self.0.get(id).expect("store should have package")
497 }
498
499 /// Gets a mutable package from the store.
500 #[must_use]
501 pub fn get_mut(&mut self, id: PackageId) -> &mut Package {
502 self.0.get_mut(id).expect("store should have package")
503 }
504
505 /// Inserts a package to the store.
506 pub fn insert(&mut self, id: PackageId, package: Package) {
507 self.0.insert(id, package);
508 }
509
510 /// Gets a package store iterator.
511 #[must_use]
512 pub fn iter(&self) -> Iter<PackageId, Package> {
513 self.0.iter()
514 }
515
516 /// Creates a package store.
517 #[must_use]
518 pub fn new() -> Self {
519 Self::default()
520 }
521}
522
523impl<'a> IntoIterator for &'a PackageStore {
524 type IntoIter = qsc_data_structures::index_map::Iter<'a, PackageId, Package>;
525 type Item = (PackageId, &'a Package);
526
527 fn into_iter(self) -> Self::IntoIter {
528 self.iter()
529 }
530}
531
532/// A trait to find elements in a package.
533pub trait PackageLookup {
534 /// Gets a block.
535 fn get_block(&self, id: BlockId) -> &Block;
536 /// Gets an expression.
537 fn get_expr(&self, id: ExprId) -> &Expr;
538 /// Gets a global.
539 fn get_global(&self, id: LocalItemId) -> Option<Global>;
540 /// Gets an item.
541 fn get_item(&self, id: LocalItemId) -> &Item;
542 /// Gets a pat.
543 fn get_pat(&self, id: PatId) -> &Pat;
544 /// Gets a statement.
545 fn get_stmt(&self, id: StmtId) -> &Stmt;
546}
547
548/// The root node of the FIR.
549/// ### Notes
550/// We maintain a dense map of ids within the package.
551/// `BlockId`, `ExprId`, `PatId`, `StmtId`, and `NodeId`s are all assigned
552/// from a type specific counter in the assigner.
553///
554/// `BlockId`, `ExprId`, `PatId`, `StmtId` ids don't leak and are only used
555/// within the containing node. Node ids are used to identify nodes within
556/// the package and require mapping from the HIR node id to the new FIR node id.
557/// `PackageId`s and `LocalItemId`s are 1:1 from the HIR and are not remapped.
558#[derive(Debug)]
559pub struct Package {
560 /// The items in the package.
561 pub items: IndexMap<LocalItemId, Item>,
562 /// The entry expression for an executable package.
563 pub entry: Option<ExprId>,
564 /// The control flow graph for the entry expression in the package.
565 pub entry_exec_graph: ExecGraph,
566 /// The blocks in the package.
567 pub blocks: IndexMap<BlockId, Block>,
568 /// The expressions in the package.
569 pub exprs: IndexMap<ExprId, Expr>,
570 /// The patterns in the package.
571 pub pats: IndexMap<PatId, Pat>,
572 /// The statements in the package.
573 pub stmts: IndexMap<StmtId, Stmt>,
574}
575
576impl Display for Package {
577 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
578 let mut indent = set_indentation(indented(f), 0);
579 write!(indent, "Package:")?;
580 indent = set_indentation(indent, 1);
581 if let Some(e) = &self.entry {
582 write!(indent, "\nEntry Expression: {e}")?;
583 }
584
585 write!(indent, "\nItems:")?;
586 indent = set_indentation(indent, 2);
587 for item in self.items.values() {
588 write!(indent, "\n{item}")?;
589 }
590
591 indent = set_indentation(indent, 1);
592 write!(indent, "\nBlocks:")?;
593 indent = set_indentation(indent, 2);
594 for block in self.blocks.values() {
595 write!(indent, "\n{block}")?;
596 }
597
598 indent = set_indentation(indent, 1);
599 write!(indent, "\nStmts:")?;
600 indent = set_indentation(indent, 2);
601 for stmt in self.stmts.values() {
602 write!(indent, "\n{stmt}")?;
603 }
604
605 indent = set_indentation(indent, 1);
606 write!(indent, "\nExprs:")?;
607 indent = set_indentation(indent, 2);
608 for expr in self.exprs.values() {
609 write!(indent, "\n{expr}")?;
610 }
611
612 indent = set_indentation(indent, 1);
613 write!(indent, "\nPats:")?;
614 indent = set_indentation(indent, 2);
615 for pat in self.pats.values() {
616 write!(indent, "\n{pat}")?;
617 }
618 Ok(())
619 }
620}
621
622impl PackageLookup for Package {
623 fn get_block(&self, id: BlockId) -> &Block {
624 self.blocks.get(id).expect("Block not found")
625 }
626
627 fn get_expr(&self, id: ExprId) -> &Expr {
628 self.exprs.get(id).expect("Expression not found")
629 }
630
631 fn get_global(&self, id: LocalItemId) -> Option<Global> {
632 match &self.items.get(id)?.kind {
633 ItemKind::Callable(callable) => Some(Global::Callable(callable)),
634 ItemKind::Namespace(..) => None,
635 ItemKind::Ty(..) => Some(Global::Udt),
636 ItemKind::Export(_name, _id) => None,
637 }
638 }
639
640 fn get_item(&self, id: LocalItemId) -> &Item {
641 self.items.get(id).expect("Item not found")
642 }
643
644 fn get_pat(&self, id: PatId) -> &Pat {
645 self.pats.get(id).expect("Pattern not found")
646 }
647
648 fn get_stmt(&self, id: StmtId) -> &Stmt {
649 self.stmts.get(id).expect("Statement not found")
650 }
651}
652
653/// An item.
654#[derive(Clone, Debug, PartialEq)]
655pub struct Item {
656 /// The ID.
657 pub id: LocalItemId,
658 /// The span.
659 pub span: Span,
660 /// The parent item.
661 pub parent: Option<LocalItemId>,
662 /// The documentation.
663 pub doc: Rc<str>,
664 /// The attributes.
665 pub attrs: Vec<Attr>,
666 /// The visibility.
667 pub visibility: Visibility,
668 /// The item kind.
669 pub kind: ItemKind,
670}
671
672impl Display for Item {
673 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
674 let mut indent = set_indentation(indented(f), 0);
675 write!(
676 indent,
677 "Item {} {} ({:?}):",
678 self.id, self.span, self.visibility
679 )?;
680
681 indent = set_indentation(indent, 1);
682 if let Some(parent) = self.parent {
683 write!(indent, "\nParent: {parent}")?;
684 }
685
686 if !self.doc.is_empty() {
687 write!(indent, "\nDoc:")?;
688 indent = set_indentation(indent, 2);
689 write!(indent, "\n{}", self.doc)?;
690 indent = set_indentation(indent, 1);
691 }
692
693 for attr in &self.attrs {
694 write!(indent, "\n{attr:?}")?;
695 }
696
697 write!(indent, "\n{}", self.kind)?;
698 Ok(())
699 }
700}
701
702/// An item kind.
703#[derive(Clone, Debug, PartialEq)]
704pub enum ItemKind {
705 /// A `function` or `operation` declaration.
706 Callable(CallableDecl),
707 /// A `namespace` declaration.
708 Namespace(Ident, Vec<LocalItemId>),
709 /// A `newtype` declaration.
710 Ty(Ident, Udt),
711 /// An export referring to another item
712 Export(Ident, ItemId),
713}
714
715impl Display for ItemKind {
716 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
717 match self {
718 ItemKind::Callable(decl) => write!(f, "{decl}"),
719 ItemKind::Namespace(name, items) => {
720 write!(f, "Namespace ({name}):")?;
721 let mut items = items.iter();
722 if let Some(item) = items.next() {
723 write!(f, " Item {item}")?;
724 for item in items {
725 write!(f, ", Item {item}")?;
726 }
727 Ok(())
728 } else {
729 write!(f, " <empty>")
730 }
731 }
732 ItemKind::Ty(name, udt) => write!(f, "Type ({name}): {udt}"),
733 ItemKind::Export(name, item) => write!(f, "Export ({name}): {item}"),
734 }
735 }
736}
737
738/// A callable declaration header.
739#[derive(Clone, Debug, PartialEq)]
740pub struct CallableDecl {
741 /// The node ID.
742 pub id: NodeId,
743 /// The span.
744 pub span: Span,
745 /// The callable kind.
746 pub kind: CallableKind,
747 /// The name of the callable.
748 pub name: Ident,
749 /// The generic parameters to the callable.
750 pub generics: Vec<GenericParam>,
751 /// The input to the callable.
752 pub input: PatId,
753 /// The return type of the callable.
754 pub output: Ty,
755 /// The functors supported by the callable.
756 pub functors: FunctorSetValue,
757 /// The callable implementation.
758 pub implementation: CallableImpl,
759}
760
761impl CallableDecl {
762 /// The type scheme of the callable.
763 #[must_use]
764 pub fn scheme<'a>(&self, f: impl Fn(PatId) -> &'a Pat) -> Scheme {
765 Scheme::new(
766 self.generics.clone(),
767 Box::new(Arrow {
768 kind: self.kind,
769 input: Box::new(f(self.input).ty.clone()),
770 output: Box::new(self.output.clone()),
771 functors: FunctorSet::Value(self.functors),
772 }),
773 )
774 }
775}
776
777impl Display for CallableDecl {
778 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
779 let mut indent = set_indentation(indented(f), 0);
780 write!(
781 indent,
782 "Callable {} {} ({}):",
783 self.id, self.span, self.kind
784 )?;
785 indent = set_indentation(indent, 1);
786 write!(indent, "\nname: {}", self.name)?;
787 if !self.generics.is_empty() {
788 write!(indent, "\ngenerics:")?;
789 indent = set_indentation(indent, 2);
790 for (ix, param) in self.generics.iter().enumerate() {
791 write!(indent, "\n{ix}: {param}")?;
792 }
793 indent = set_indentation(indent, 1);
794 }
795 write!(indent, "\ninput: {}", self.input)?;
796 write!(indent, "\noutput: {}", self.output)?;
797 write!(indent, "\nfunctors: {}", self.functors)?;
798 write!(indent, "\nimplementation: {}", self.implementation)?;
799 Ok(())
800 }
801}
802
803/// A callable implementations.
804#[derive(Clone, Debug, PartialEq)]
805pub enum CallableImpl {
806 /// An intrinsic callable implementation.
807 Intrinsic,
808 /// A specialized callable implementation.
809 Spec(SpecImpl),
810 /// An intrinsic with a simulation override.
811 SimulatableIntrinsic(SpecDecl),
812}
813
814impl Display for CallableImpl {
815 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
816 let mut indent = set_indentation(indented(f), 0);
817 match self {
818 CallableImpl::Intrinsic => {
819 write!(indent, "Instrinsic")?;
820 }
821 CallableImpl::Spec(spec_impl) => {
822 write!(indent, "Spec:")?;
823 indent = set_indentation(indent, 1);
824 write!(indent, "\n{spec_impl}")?;
825 }
826 CallableImpl::SimulatableIntrinsic(spec_decl) => {
827 write!(indent, "SimulatableIntrinsic:")?;
828 indent = set_indentation(indent, 1);
829 write!(indent, "\n{spec_decl}")?;
830 }
831 }
832
833 Ok(())
834 }
835}
836
837/// A specialized implementation.
838#[derive(Clone, Debug, PartialEq)]
839pub struct SpecImpl {
840 /// The body implementation.
841 pub body: SpecDecl,
842 /// The adjoint specialization.
843 pub adj: Option<SpecDecl>,
844 /// The controlled specialization.
845 pub ctl: Option<SpecDecl>,
846 /// The controlled adjoint specialization.
847 pub ctl_adj: Option<SpecDecl>,
848}
849
850impl Display for SpecImpl {
851 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
852 let mut indent = set_indentation(indented(f), 0);
853 write!(indent, "SpecImpl:")?;
854 indent = set_indentation(indent, 1);
855 write!(indent, "\nbody: {}", self.body)?;
856 match &self.adj {
857 Some(spec) => write!(indent, "\nadj: {spec}")?,
858 None => write!(indent, "\nadj: <none>")?,
859 }
860 match &self.ctl {
861 Some(spec) => write!(indent, "\nctl: {spec}")?,
862 None => write!(indent, "\nctl: <none>")?,
863 }
864 match &self.ctl_adj {
865 Some(spec) => write!(indent, "\nctl-adj: {spec}")?,
866 None => write!(indent, "\nctl-adj: <none>")?,
867 }
868 Ok(())
869 }
870}
871
872/// A specialization declaration.
873#[derive(Clone, Debug, PartialEq)]
874pub struct SpecDecl {
875 /// The node ID.
876 pub id: NodeId,
877 /// The span.
878 pub span: Span,
879 /// The block that implements the specialization.
880 pub block: BlockId,
881 /// The input of the specialization.
882 pub input: Option<PatId>,
883 /// The flattened control flow graph for the execution of the specialization.
884 pub exec_graph: ExecGraph,
885}
886
887impl Display for SpecDecl {
888 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
889 write!(
890 f,
891 "SpecDecl {} {}: {:?} {}",
892 self.id, self.span, self.input, self.block
893 )
894 }
895}
896
897/// An execution graph represented by a reference counted vector of nodes.
898pub type ExecGraph = Rc<[ExecGraphNode]>;
899
900#[derive(Copy, Clone, Debug, PartialEq)]
901/// A node within the control flow graph.
902pub enum ExecGraphNode {
903 /// A binding of a value to a variable.
904 Bind(PatId),
905 /// An expression to execute.
906 Expr(ExprId),
907 /// An unconditional jump with to given location.
908 Jump(u32),
909 /// A conditional jump with to given location, where the jump is only taken if the condition is
910 /// true.
911 JumpIf(u32),
912 /// A conditional jump with to given location, where the jump is only taken if the condition is
913 /// false.
914 JumpIfNot(u32),
915 /// An indication that the current accumulated result value should be stored into the value stack.
916 Store,
917 /// A no-op Unit node that tells execution to insert a unit value into the current accumulated result.
918 Unit,
919 /// The end of the control flow graph.
920 Ret,
921 /// The end of the control flow graph plus a pop of the current debug frame. Used instead of `Ret`
922 /// when debugging.
923 RetFrame,
924 /// A statement to track for debugging.
925 Stmt(StmtId),
926 /// A push of a new scope, used when tracking variables for debugging.
927 PushScope,
928 /// A pop of the current scope, used when tracking variables for debugging.
929 PopScope,
930}
931
932/// A sequenced block of statements.
933#[derive(Clone, Debug, PartialEq)]
934pub struct Block {
935 /// The node ID.
936 pub id: BlockId,
937 /// The span.
938 pub span: Span,
939 /// The block type.
940 pub ty: Ty,
941 /// The statements in the block.
942 pub stmts: Vec<StmtId>,
943}
944
945impl Display for Block {
946 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
947 if self.stmts.is_empty() {
948 write!(f, "Block {} {}: <empty>", self.id, self.span)?;
949 } else {
950 let mut indent = set_indentation(indented(f), 0);
951 write!(
952 indent,
953 "Block {} {} [Type {}]:",
954 self.id, self.span, self.ty
955 )?;
956 indent = set_indentation(indent, 1);
957 for s in &self.stmts {
958 write!(indent, "\n{s}")?;
959 }
960 }
961 Ok(())
962 }
963}
964
965/// A statement.
966#[derive(Clone, Debug, PartialEq)]
967pub struct Stmt {
968 /// The stmt ID.
969 pub id: StmtId,
970 /// The span.
971 pub span: Span,
972 /// The statement kind.
973 pub kind: StmtKind,
974 /// The locations within the containing control flow graph for the current statement.
975 pub exec_graph_range: ops::Range<usize>,
976}
977
978impl Display for Stmt {
979 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
980 write!(f, "Stmt {} {}: {}", self.id, self.span, self.kind)
981 }
982}
983
984/// A statement kind.
985#[derive(Clone, Debug, PartialEq)]
986pub enum StmtKind {
987 /// An expression without a trailing semicolon.
988 Expr(ExprId),
989 /// An item.
990 Item(LocalItemId),
991 /// A let or mutable binding: `let a = b;` or `mutable x = b;`.
992 Local(Mutability, PatId, ExprId),
993 /// An expression with a trailing semicolon.
994 Semi(ExprId),
995}
996
997impl Display for StmtKind {
998 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
999 let mut indent = set_indentation(indented(f), 0);
1000 match self {
1001 StmtKind::Expr(e) => write!(indent, "Expr: {e}")?,
1002 StmtKind::Item(item) => write!(indent, "Item: {item}")?,
1003 StmtKind::Local(m, lhs, rhs) => {
1004 write!(indent, "Local ({m:?}):")?;
1005 indent = set_indentation(indent, 1);
1006 write!(indent, "\n{lhs}")?;
1007 write!(indent, "\n{rhs}")?;
1008 }
1009 StmtKind::Semi(e) => write!(indent, "Semi: {e}")?,
1010 }
1011 Ok(())
1012 }
1013}
1014
1015/// An expression.
1016#[derive(Clone, Debug, PartialEq)]
1017pub struct Expr {
1018 /// The expr ID.
1019 pub id: ExprId,
1020 /// The span.
1021 pub span: Span,
1022 /// The expression type.
1023 pub ty: Ty,
1024 /// The expression kind.
1025 pub kind: ExprKind,
1026 /// The locations within the containing control flow graph for the current expression.
1027 pub exec_graph_range: ops::Range<usize>,
1028}
1029
1030impl Display for Expr {
1031 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1032 write!(
1033 f,
1034 "Expr {} {} [Type {}]: {}",
1035 self.id, self.span, self.ty, self.kind
1036 )
1037 }
1038}
1039
1040/// An expression kind.
1041#[derive(Clone, Debug, PartialEq)]
1042pub enum ExprKind {
1043 /// An array: `[a, b, c]`.
1044 Array(Vec<ExprId>),
1045 /// An array of literal values, ie: `[1, 2, 3]`.
1046 ArrayLit(Vec<ExprId>),
1047 /// An array constructed by repeating a value: `[a, size = b]`.
1048 ArrayRepeat(ExprId, ExprId),
1049 /// An assignment: `set a = b`.
1050 Assign(ExprId, ExprId),
1051 /// An assignment with a compound operator. For example: `set a += b`.
1052 AssignOp(BinOp, ExprId, ExprId),
1053 /// An assignment with a compound field update operator: `set a w/= B <- c`.
1054 AssignField(ExprId, Field, ExprId),
1055 /// An assignment with a compound index update operator: `set a w/= b <- c`.
1056 AssignIndex(ExprId, ExprId, ExprId),
1057 /// A binary operator.
1058 BinOp(BinOp, ExprId, ExprId),
1059 /// A block: `{ ... }`.
1060 Block(BlockId),
1061 /// A call: `a(b)`.
1062 Call(ExprId, ExprId),
1063 /// A closure that fixes the vector of local variables as arguments to the callable item.
1064 Closure(Vec<LocalVarId>, LocalItemId),
1065 /// A failure: `fail "message"`.
1066 Fail(ExprId),
1067 /// A field accessor: `a::F` or `a.F`.
1068 Field(ExprId, Field),
1069 /// An unspecified expression, _, which may indicate partial application or discards
1070 Hole,
1071 /// An if expression with an optional else block: `if a { ... } else { ... }`.
1072 ///
1073 /// Note that, as a special case, `elif ...` is effectively parsed as `else if ...`, without a
1074 /// block wrapping the `if`. This distinguishes `elif ...` from `else { if ... }`, which does
1075 /// have a block.
1076 If(ExprId, ExprId, Option<ExprId>),
1077 /// An index accessor: `a[b]`.
1078 Index(ExprId, ExprId),
1079 /// A literal.
1080 Lit(Lit),
1081 /// A range: `start..step..end`, `start..end`, `start...`, `...end`, or `...`.
1082 Range(Option<ExprId>, Option<ExprId>, Option<ExprId>),
1083 /// A return: `return a`.
1084 Return(ExprId),
1085 /// A struct constructor.
1086 Struct(Res, Option<ExprId>, Vec<FieldAssign>),
1087 /// A string.
1088 String(Vec<StringComponent>),
1089 /// Update array index: `a w/ b <- c`.
1090 UpdateIndex(ExprId, ExprId, ExprId),
1091 /// A tuple: `(a, b, c)`.
1092 Tuple(Vec<ExprId>),
1093 /// A unary operator.
1094 UnOp(UnOp, ExprId),
1095 /// A record field update: `a w/ B <- c`.
1096 UpdateField(ExprId, Field, ExprId),
1097 /// A variable and its generic arguments.
1098 Var(Res, Vec<GenericArg>),
1099 /// A while loop: `while a { ... }`.
1100 While(ExprId, BlockId),
1101}
1102
1103impl Display for ExprKind {
1104 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1105 let mut indent = set_indentation(indented(f), 0);
1106 match self {
1107 ExprKind::Array(exprs) | ExprKind::ArrayLit(exprs) => display_array(indent, exprs)?,
1108 ExprKind::ArrayRepeat(val, size) => display_array_repeat(indent, *val, *size)?,
1109 ExprKind::Assign(lhs, rhs) => display_assign(indent, *lhs, *rhs)?,
1110 ExprKind::AssignOp(op, lhs, rhs) => display_assign_op(indent, *op, *lhs, *rhs)?,
1111 ExprKind::AssignField(record, field, replace) => {
1112 display_assign_field(indent, *record, field, *replace)?;
1113 }
1114 ExprKind::AssignIndex(container, item, replace) => {
1115 display_assign_index(indent, *container, *item, *replace)?;
1116 }
1117 ExprKind::BinOp(op, lhs, rhs) => display_bin_op(indent, *op, *lhs, *rhs)?,
1118 ExprKind::Block(block) => write!(indent, "Expr Block: {block}")?,
1119 ExprKind::Call(callable, arg) => display_call(indent, *callable, *arg)?,
1120 ExprKind::Closure(args, callable) => display_closure(indent, args, *callable)?,
1121 ExprKind::Fail(e) => write!(indent, "Fail: {e}")?,
1122 ExprKind::Field(expr, field) => display_field(indent, *expr, field)?,
1123 ExprKind::Hole => write!(indent, "Hole")?,
1124 ExprKind::If(cond, body, els) => display_if(indent, *cond, *body, *els)?,
1125 ExprKind::Index(array, index) => display_index(indent, *array, *index)?,
1126 ExprKind::Lit(lit) => write!(indent, "Lit: {lit}")?,
1127 ExprKind::Range(start, step, end) => display_range(indent, *start, *step, *end)?,
1128 ExprKind::Return(e) => write!(indent, "Return: {e}")?,
1129 ExprKind::Struct(name, copy, fields) => display_struct(indent, name, *copy, fields)?,
1130 ExprKind::String(components) => display_string(indent, components)?,
1131 ExprKind::UpdateIndex(expr1, expr2, expr3) => {
1132 display_update_index(indent, *expr1, *expr2, *expr3)?;
1133 }
1134 ExprKind::Tuple(exprs) => display_tuple(indent, exprs)?,
1135 ExprKind::UnOp(op, expr) => display_un_op(indent, *op, *expr)?,
1136 ExprKind::UpdateField(record, field, replace) => {
1137 display_update_field(indent, *record, field, *replace)?;
1138 }
1139 ExprKind::Var(res, args) => display_var(indent, *res, args)?,
1140 ExprKind::While(cond, block) => display_while(indent, *cond, *block)?,
1141 }
1142 Ok(())
1143 }
1144}
1145
1146fn display_array(mut indent: Indented<Formatter>, exprs: &Vec<ExprId>) -> fmt::Result {
1147 write!(indent, "Array:")?;
1148 indent = set_indentation(indent, 1);
1149 for e in exprs {
1150 write!(indent, "\n{e}")?;
1151 }
1152 Ok(())
1153}
1154
1155fn display_array_repeat(mut indent: Indented<Formatter>, val: ExprId, size: ExprId) -> fmt::Result {
1156 write!(indent, "ArrayRepeat:")?;
1157 indent = set_indentation(indent, 1);
1158 write!(indent, "\n{val}")?;
1159 write!(indent, "\n{size}")?;
1160 Ok(())
1161}
1162
1163fn display_assign(mut indent: Indented<Formatter>, lhs: ExprId, rhs: ExprId) -> fmt::Result {
1164 write!(indent, "Assign:")?;
1165 indent = set_indentation(indent, 1);
1166 write!(indent, "\n{lhs}")?;
1167 write!(indent, "\n{rhs}")?;
1168 Ok(())
1169}
1170
1171fn display_assign_op(
1172 mut indent: Indented<Formatter>,
1173 op: BinOp,
1174 lhs: ExprId,
1175 rhs: ExprId,
1176) -> fmt::Result {
1177 write!(indent, "AssignOp ({op:?}):")?;
1178 indent = set_indentation(indent, 1);
1179 write!(indent, "\n{lhs}")?;
1180 write!(indent, "\n{rhs}")?;
1181 Ok(())
1182}
1183
1184fn display_assign_field(
1185 mut indent: Indented<Formatter>,
1186 record: ExprId,
1187 field: &Field,
1188 replace: ExprId,
1189) -> fmt::Result {
1190 write!(indent, "AssignField:")?;
1191 indent = set_indentation(indent, 1);
1192 write!(indent, "\n{record}")?;
1193 write!(indent, "\n{field}")?;
1194 write!(indent, "\n{replace}")?;
1195 Ok(())
1196}
1197
1198fn display_assign_index(
1199 mut indent: Indented<Formatter>,
1200 array: ExprId,
1201 index: ExprId,
1202 replace: ExprId,
1203) -> fmt::Result {
1204 write!(indent, "AssignIndex:")?;
1205 indent = set_indentation(indent, 1);
1206 write!(indent, "\n{array}")?;
1207 write!(indent, "\n{index}")?;
1208 write!(indent, "\n{replace}")?;
1209 Ok(())
1210}
1211
1212fn display_bin_op(
1213 mut indent: Indented<Formatter>,
1214 op: BinOp,
1215 lhs: ExprId,
1216 rhs: ExprId,
1217) -> fmt::Result {
1218 write!(indent, "BinOp ({op:?}):")?;
1219 indent = set_indentation(indent, 1);
1220 write!(indent, "\n{lhs}")?;
1221 write!(indent, "\n{rhs}")?;
1222 Ok(())
1223}
1224
1225fn display_call(mut indent: Indented<Formatter>, callable: ExprId, arg: ExprId) -> fmt::Result {
1226 write!(indent, "Call:")?;
1227 indent = set_indentation(indent, 1);
1228 write!(indent, "\n{callable}")?;
1229 write!(indent, "\n{arg}")?;
1230 Ok(())
1231}
1232
1233fn display_closure(
1234 mut f: Indented<Formatter>,
1235 args: &[LocalVarId],
1236 callable: LocalItemId,
1237) -> fmt::Result {
1238 f.write_str("Closure([")?;
1239 let mut args = args.iter();
1240 if let Some(arg) = args.next() {
1241 write!(f, "{arg}")?;
1242 }
1243 for arg in args {
1244 write!(f, ", {arg}")?;
1245 }
1246 write!(f, "], {callable})")
1247}
1248
1249fn display_field(mut indent: Indented<Formatter>, expr: ExprId, field: &Field) -> fmt::Result {
1250 write!(indent, "Field:")?;
1251 indent = set_indentation(indent, 1);
1252 write!(indent, "\n{expr}")?;
1253 write!(indent, "\n{field:?}")?;
1254 Ok(())
1255}
1256
1257fn display_if(
1258 mut indent: Indented<Formatter>,
1259 cond: ExprId,
1260 body: ExprId,
1261 els: Option<ExprId>,
1262) -> fmt::Result {
1263 write!(indent, "If:")?;
1264 indent = set_indentation(indent, 1);
1265 write!(indent, "\n{cond}")?;
1266 write!(indent, "\n{body}")?;
1267 if let Some(e) = els {
1268 write!(indent, "\n{e}")?;
1269 }
1270 Ok(())
1271}
1272
1273fn display_index(mut indent: Indented<Formatter>, array: ExprId, index: ExprId) -> fmt::Result {
1274 write!(indent, "Index:")?;
1275 indent = set_indentation(indent, 1);
1276 write!(indent, "\n{array}")?;
1277 write!(indent, "\n{index}")?;
1278 Ok(())
1279}
1280
1281fn display_range(
1282 mut indent: Indented<Formatter>,
1283 start: Option<ExprId>,
1284 step: Option<ExprId>,
1285 end: Option<ExprId>,
1286) -> fmt::Result {
1287 write!(indent, "Range:")?;
1288 indent = set_indentation(indent, 1);
1289 match start {
1290 Some(e) => write!(indent, "\n{e}")?,
1291 None => write!(indent, "\n<no start>")?,
1292 }
1293 match step {
1294 Some(e) => write!(indent, "\n{e}")?,
1295 None => write!(indent, "\n<no step>")?,
1296 }
1297 match end {
1298 Some(e) => write!(indent, "\n{e}")?,
1299 None => write!(indent, "\n<no end>")?,
1300 }
1301 Ok(())
1302}
1303
1304fn display_struct(
1305 mut indent: Indented<Formatter>,
1306 name: &Res,
1307 copy: Option<ExprId>,
1308 fields: &Vec<FieldAssign>,
1309) -> fmt::Result {
1310 write!(indent, "Struct ({name}):")?;
1311 if copy.is_none() && fields.is_empty() {
1312 write!(indent, " <empty>")?;
1313 return Ok(());
1314 }
1315 indent = set_indentation(indent, 1);
1316 if let Some(copy) = copy {
1317 write!(indent, "\nCopy: {copy}")?;
1318 }
1319 for field in fields {
1320 write!(indent, "\n{field}")?;
1321 }
1322 Ok(())
1323}
1324
1325fn display_string(mut indent: Indented<Formatter>, components: &[StringComponent]) -> fmt::Result {
1326 write!(indent, "String:")?;
1327 indent = set_indentation(indent, 1);
1328 for component in components {
1329 match component {
1330 StringComponent::Expr(expr) => write!(indent, "\nExpr: {expr}")?,
1331 StringComponent::Lit(str) => write!(indent, "\nLit: {str:?}")?,
1332 }
1333 }
1334
1335 Ok(())
1336}
1337
1338fn display_update_index(
1339 mut indent: Indented<Formatter>,
1340 expr1: ExprId,
1341 expr2: ExprId,
1342 expr3: ExprId,
1343) -> fmt::Result {
1344 write!(indent, "UpdateIndex:")?;
1345 indent = set_indentation(indent, 1);
1346 write!(indent, "\n{expr1}")?;
1347 write!(indent, "\n{expr2}")?;
1348 write!(indent, "\n{expr3}")?;
1349 Ok(())
1350}
1351
1352fn display_tuple(mut indent: Indented<Formatter>, exprs: &Vec<ExprId>) -> fmt::Result {
1353 if exprs.is_empty() {
1354 write!(indent, "Unit")?;
1355 } else {
1356 write!(indent, "Tuple:")?;
1357 indent = set_indentation(indent, 1);
1358 for e in exprs {
1359 write!(indent, "\n{e}")?;
1360 }
1361 }
1362 Ok(())
1363}
1364
1365fn display_un_op(mut indent: Indented<Formatter>, op: UnOp, expr: ExprId) -> fmt::Result {
1366 write!(indent, "UnOp ({op}):")?;
1367 indent = set_indentation(indent, 1);
1368 write!(indent, "\n{expr}")?;
1369 Ok(())
1370}
1371
1372fn display_update_field(
1373 mut indent: Indented<Formatter>,
1374 record: ExprId,
1375 field: &Field,
1376 replace: ExprId,
1377) -> fmt::Result {
1378 write!(indent, "UpdateField:")?;
1379 indent = set_indentation(indent, 1);
1380 write!(indent, "\n{record}")?;
1381 write!(indent, "\n{field}")?;
1382 write!(indent, "\n{replace}")?;
1383 Ok(())
1384}
1385
1386fn display_var(mut f: Indented<Formatter>, res: Res, args: &[GenericArg]) -> fmt::Result {
1387 if args.is_empty() {
1388 write!(f, "Var: {res}")
1389 } else {
1390 write!(f, "Var:")?;
1391 f = set_indentation(f, 1);
1392 write!(f, "\nres: {res}")?;
1393 write!(f, "\ngenerics:")?;
1394 f = set_indentation(f, 2);
1395 for arg in args {
1396 write!(f, "\n{arg}")?;
1397 }
1398 Ok(())
1399 }
1400}
1401
1402fn display_while(mut indent: Indented<Formatter>, cond: ExprId, block: BlockId) -> fmt::Result {
1403 write!(indent, "While:")?;
1404 indent = set_indentation(indent, 1);
1405 write!(indent, "\n{cond}")?;
1406 write!(indent, "\n{block}")?;
1407 Ok(())
1408}
1409
1410/// A field assignment in a struct constructor expression.
1411#[derive(Clone, Debug, PartialEq)]
1412pub struct FieldAssign {
1413 /// The node ID.
1414 pub id: NodeId,
1415 /// The span.
1416 pub span: Span,
1417 /// The field to assign.
1418 pub field: Field,
1419 /// The value to assign to the field.
1420 pub value: ExprId,
1421}
1422
1423impl Display for FieldAssign {
1424 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1425 write!(
1426 f,
1427 "FieldsAssign {} {}: ({}) {}",
1428 self.id, self.span, self.field, self.value
1429 )
1430 }
1431}
1432
1433/// A string component.
1434#[derive(Clone, Debug, PartialEq)]
1435pub enum StringComponent {
1436 /// An expression.
1437 Expr(ExprId),
1438 /// A string literal.
1439 Lit(Rc<str>),
1440}
1441
1442/// A pattern.
1443#[derive(Clone, Debug, Eq, PartialEq)]
1444pub struct Pat {
1445 /// The node ID.
1446 pub id: PatId,
1447 /// The span.
1448 pub span: Span,
1449 /// The pattern type.
1450 pub ty: Ty,
1451 /// The pattern kind.
1452 pub kind: PatKind,
1453}
1454
1455impl Display for Pat {
1456 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1457 write!(
1458 f,
1459 "Pat {} {} [Type {}]: {}",
1460 self.id, self.span, self.ty, self.kind
1461 )
1462 }
1463}
1464
1465/// A pattern kind.
1466#[derive(Clone, Debug, Eq, PartialEq)]
1467pub enum PatKind {
1468 /// A binding.
1469 Bind(Ident),
1470 /// A discarded binding, `_`.
1471 Discard,
1472 /// A tuple: `(a, b, c)`.
1473 Tuple(Vec<PatId>),
1474}
1475
1476impl Display for PatKind {
1477 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1478 let mut indent = set_indentation(indented(f), 0);
1479 match self {
1480 PatKind::Bind(id) => {
1481 write!(indent, "Bind: {id}")?;
1482 }
1483 PatKind::Discard => write!(indent, "Discard")?,
1484 PatKind::Tuple(ps) => {
1485 if ps.is_empty() {
1486 write!(indent, "Unit")?;
1487 } else {
1488 write!(indent, "Tuple:")?;
1489 indent = set_indentation(indent, 1);
1490 for p in ps {
1491 write!(indent, "\n{p}")?;
1492 }
1493 }
1494 }
1495 }
1496 Ok(())
1497 }
1498}
1499
1500/// An identifier.
1501#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1502pub struct Ident {
1503 /// The node ID.
1504 pub id: LocalVarId,
1505 /// The span.
1506 pub span: Span,
1507 /// The identifier name.
1508 pub name: Rc<str>,
1509}
1510
1511impl Display for Ident {
1512 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1513 write!(f, "Ident {} {} \"{}\"", self.id, self.span, self.name)
1514 }
1515}
1516
1517/// An attribute.
1518#[derive(Clone, Debug, PartialEq)]
1519pub enum Attr {
1520 /// Indicates that a callable is an entry point to a program.
1521 EntryPoint,
1522}
1523
1524/// A field.
1525#[derive(Clone, Debug, Eq, PartialEq)]
1526pub enum Field {
1527 /// A field path.
1528 Path(FieldPath),
1529 /// A primitive field for a built-in type.
1530 Prim(PrimField),
1531 /// An invalid field.
1532 Err,
1533}
1534
1535impl Display for Field {
1536 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1537 match self {
1538 Field::Path(path) => write!(f, "Path({:?})", path.indices),
1539 Field::Prim(prim) => write!(f, "Prim({prim:?}"),
1540 Field::Err => f.write_str("Err"),
1541 }
1542 }
1543}
1544
1545/// A path to a field in a tuple or user-defined type.
1546#[derive(Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
1547pub struct FieldPath {
1548 /// The tuple item indices to follow in order from top to bottom.
1549 pub indices: Vec<usize>,
1550}
1551
1552/// A primitive field for a built-in type.
1553#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1554pub enum PrimField {
1555 /// The start of a range.
1556 Start,
1557 /// The step of a range.
1558 Step,
1559 /// The end of a range.
1560 End,
1561}
1562
1563impl FromStr for PrimField {
1564 type Err = ();
1565
1566 fn from_str(s: &str) -> result::Result<Self, <Self as FromStr>::Err> {
1567 match s {
1568 "Start" => Ok(Self::Start),
1569 "Step" => Ok(Self::Step),
1570 "End" => Ok(Self::End),
1571 _ => Err(()),
1572 }
1573 }
1574}
1575
1576/// The visibility of a declaration.
1577#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1578pub enum Visibility {
1579 /// Visible everywhere.
1580 Public,
1581 /// Visible within a package.
1582 Internal,
1583}
1584
1585/// A callable kind.
1586#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1587pub enum CallableKind {
1588 /// A function.
1589 Function,
1590 /// An operation.
1591 Operation,
1592}
1593
1594impl Display for CallableKind {
1595 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1596 match self {
1597 CallableKind::Function => f.write_str("function"),
1598 CallableKind::Operation => f.write_str("operation"),
1599 }
1600 }
1601}
1602
1603/// The mutability of a binding.
1604#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1605pub enum Mutability {
1606 /// An immutable binding.
1607 Immutable,
1608 /// A mutable binding.
1609 Mutable,
1610}
1611
1612/// The source of an allocated qubit.
1613#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1614pub enum QubitSource {
1615 /// A qubit initialized to the zero state.
1616 Fresh,
1617 /// A qubit borrowed from another part of the program that may be in any state, and is expected
1618 /// to be returned to that state before being released.
1619 Dirty,
1620}
1621
1622/// A literal.
1623#[derive(Clone, Debug, PartialEq)]
1624pub enum Lit {
1625 /// A big integer literal.
1626 BigInt(BigInt),
1627 /// A boolean literal.
1628 Bool(bool),
1629 /// A floating-point literal.
1630 Double(f64),
1631 /// An integer literal.
1632 Int(i64),
1633 /// A Pauli operator literal.
1634 Pauli(Pauli),
1635 /// A measurement result literal.
1636 Result(Result),
1637}
1638
1639impl Display for Lit {
1640 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1641 match self {
1642 Lit::BigInt(val) => write!(f, "BigInt({val})")?,
1643 Lit::Bool(val) => write!(f, "Bool({val})")?,
1644 Lit::Double(val) => write!(f, "Double({val})")?,
1645 Lit::Int(val) => write!(f, "Int({val})")?,
1646 Lit::Pauli(val) => write!(f, "Pauli({val:?})")?,
1647 Lit::Result(val) => write!(f, "Result({val:?})")?,
1648 }
1649 Ok(())
1650 }
1651}
1652
1653/// A measurement result.
1654#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1655pub enum Result {
1656 /// The zero eigenvalue.
1657 Zero,
1658 /// The one eigenvalue.
1659 One,
1660}
1661
1662/// A Pauli operator.
1663#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1664pub enum Pauli {
1665 /// The Pauli I operator.
1666 I,
1667 /// The Pauli X operator.
1668 X,
1669 /// The Pauli Y operator.
1670 Y,
1671 /// The Pauli Z operator.
1672 Z,
1673}
1674
1675/// A functor that may be applied to an operation.
1676#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1677pub enum Functor {
1678 /// The adjoint functor.
1679 Adj,
1680 /// The controlled functor.
1681 Ctl,
1682}
1683
1684impl Display for Functor {
1685 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1686 match self {
1687 Functor::Adj => f.write_str("Adj"),
1688 Functor::Ctl => f.write_str("Ctl"),
1689 }
1690 }
1691}
1692
1693/// A unary operator.
1694#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1695pub enum UnOp {
1696 /// A functor application.
1697 Functor(Functor),
1698 /// Negation: `-`.
1699 Neg,
1700 /// Bitwise NOT: `~~~`.
1701 NotB,
1702 /// Logical NOT: `not`.
1703 NotL,
1704 /// A leading `+`.
1705 Pos,
1706 /// Unwrap a user-defined type: `!`.
1707 Unwrap,
1708}
1709
1710impl Display for UnOp {
1711 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1712 match self {
1713 UnOp::Functor(func) => write!(f, "Functor {func:?}")?,
1714 _ => fmt::Debug::fmt(self, f)?,
1715 }
1716 Ok(())
1717 }
1718}
1719
1720/// A binary operator.
1721#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1722pub enum BinOp {
1723 /// Addition: `+`.
1724 Add,
1725 /// Bitwise AND: `&&&`.
1726 AndB,
1727 /// Logical AND: `and`.
1728 AndL,
1729 /// Division: `/`.
1730 Div,
1731 /// Equality: `==`.
1732 Eq,
1733 /// Exponentiation: `^`.
1734 Exp,
1735 /// Greater than: `>`.
1736 Gt,
1737 /// Greater than or equal: `>=`.
1738 Gte,
1739 /// Less than: `<`.
1740 Lt,
1741 /// Less than or equal: `<=`.
1742 Lte,
1743 /// Modulus: `%`.
1744 Mod,
1745 /// Multiplication: `*`.
1746 Mul,
1747 /// Inequality: `!=`.
1748 Neq,
1749 /// Bitwise OR: `|||`.
1750 OrB,
1751 /// Logical OR: `or`.
1752 OrL,
1753 /// Shift left: `<<<`.
1754 Shl,
1755 /// Shift right: `>>>`.
1756 Shr,
1757 /// Subtraction: `-`.
1758 Sub,
1759 /// Bitwise XOR: `^^^`.
1760 XorB,
1761}
1762