qualia_q_forge/qasm/
mod.rs1use qualia_core_db::q_hash;
6
7pub mod parser;
8pub use parser::*;
9
10#[derive(Debug, Clone)]
12pub struct QasmProgram {
13 pub statements: [QasmStatement; 256],
14 pub statement_count: usize,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Default)]
19pub struct GateBodyOp {
20 pub name_hash: u64,
21 pub target_indices: [u8; 4],
22 pub num_targets: u8,
23}
24
25#[derive(Debug, Clone, Copy)]
27pub enum QasmStatement {
28 Empty,
29 GateDecl {
30 name_hash: u64,
31 num_qubits: u8,
32 body_count: u8,
33 body_ops: [GateBodyOp; 16],
34 },
35 GateCall {
36 name_hash: u64,
37 target_qubits: [u16; 4],
38 num_targets: u8,
39 params: [f64; 4],
40 num_params: u8,
41 },
42 QubitDecl {
43 name_hash: u64,
44 size: u16,
45 },
46}
47
48impl Default for QasmStatement {
49 fn default() -> Self {
50 QasmStatement::Empty
51 }
52}
53
54impl QasmProgram {
55 pub fn new() -> Self {
57 Self {
58 statements: [QasmStatement::Empty; 256],
59 statement_count: 0,
60 }
61 }
62}
63
64impl Default for QasmProgram {
65 fn default() -> Self {
66 Self::new()
67 }
68}
69
70impl QasmProgram {
71 pub fn push(&mut self, statement: QasmStatement) -> Result<(), &'static str> {
73 if self.statement_count >= 256 {
74 return Err("AST capacity exceeded");
75 }
76 self.statements[self.statement_count] = statement;
77 self.statement_count += 1;
78 Ok(())
79 }
80
81 pub fn expand_composite_gates(&self) -> Result<QasmProgram, &'static str> {
83 let mut expanded = QasmProgram::new();
84 for i in 0..self.statement_count {
85 match self.statements[i] {
86 QasmStatement::GateCall {
87 name_hash,
88 target_qubits,
89 num_targets,
90 params: _,
91 num_params: _,
92 } => {
93 let mut found_decl = None;
94 for j in 0..self.statement_count {
95 if let QasmStatement::GateDecl {
96 name_hash: decl_hash,
97 num_qubits,
98 body_count,
99 body_ops,
100 } = self.statements[j]
101 {
102 if decl_hash == name_hash && body_count > 0 {
103 found_decl = Some((num_qubits, body_count, body_ops));
104 break;
105 }
106 }
107 }
108
109 if let Some((_num_qubits, body_count, body_ops)) = found_decl {
110 for k in 0..body_count as usize {
111 let op = body_ops[k];
112 let mut mapped_targets = [0u16; 4];
113 for t in 0..op.num_targets as usize {
114 let formal_idx = op.target_indices[t] as usize;
115 if formal_idx < num_targets as usize {
116 mapped_targets[t] = target_qubits[formal_idx];
117 }
118 }
119 expanded.push(QasmStatement::GateCall {
120 name_hash: op.name_hash,
121 target_qubits: mapped_targets,
122 num_targets: op.num_targets,
123 params: [0.0; 4],
124 num_params: 0,
125 })?;
126 }
127 } else {
128 expanded.push(self.statements[i])?;
129 }
130 }
131 other => {
132 expanded.push(other)?;
133 }
134 }
135 }
136 Ok(expanded)
137 }
138}