graphix-qasm-parser 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Thierry Martinez
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: graphix-qasm-parser
3
+ Version: 0.1.0
4
+ Author-email: Thierry Martinez <Thierry.Martinez@inria.fr>
5
+ Maintainer-email: Thierry Martinez <Thierry.Martinez@inria.fr>
6
+ License-File: LICENSE
7
+ Requires-Dist: graphix>=0.3.1
8
+ Requires-Dist: openqasm-parser>=3.1.0
9
+ Provides-Extra: dev
10
+ Requires-Dist: mypy==1.17.0; extra == "dev"
11
+ Requires-Dist: pyright; extra == "dev"
12
+ Requires-Dist: ruff==0.12.5; extra == "dev"
13
+ Requires-Dist: nox==2025.5.1; extra == "dev"
14
+ Requires-Dist: pytest; extra == "dev"
15
+ Dynamic: license-file
@@ -0,0 +1,76 @@
1
+ # Graphix OpenQASM Parser
2
+
3
+ `graphix-qasm-parser` is a plugin for the
4
+ [Graphix](https://github.com/TeamGraphix/graphix) library that parses
5
+ OpenQASM circuit specifications into
6
+ `graphix.transpiler.Circuit` objects, which can then be transpiled
7
+ into MBQC patterns.
8
+
9
+ It is distributed as a separate plugin because it depends on
10
+ [`openqasm-parser`](https://github.com/qat-inria/openqasm-parser/).
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ pip install https://github.com/TeamGraphix/graphix-qasm-parser.git
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ### Parsing a string:
21
+
22
+ ```python
23
+ from graphix_qasm_parser import OpenQASMParser
24
+
25
+ s = """
26
+ include "qelib1.inc";
27
+ qubit q;
28
+ rz(5*pi/4) q;
29
+ """
30
+ parser = OpenQASMParser()
31
+ circuit = parser.parse_str(s)
32
+ pattern = circuit.transpile().pattern
33
+ print(pattern)
34
+ ```
35
+
36
+ ### Parsing a file:
37
+
38
+ ```python
39
+ circuit = parser.parse_file("my_circuit.qasm")
40
+ ```
41
+
42
+ ## Supported Specification
43
+
44
+ ### [Qubits](https://openqasm.com/language/types.html#qubits)
45
+
46
+ - Single-qubit registers: `qubit q`, or the old syntax `qreg q`.
47
+
48
+ - Qubit register arrays: `qubit[n] q`, or the old syntax `qreg q[n]`.
49
+
50
+ ### Supported Gates
51
+
52
+ | OpenQASM gate | Graphix instruction |
53
+ |------------------------------------------------------------------|---------------------|
54
+ | [ccx](https://openqasm.com/language/standard_library.html#ccx) | CCX |
55
+ | [crz](https://openqasm.com/language/standard_library.html#crz) | RZZ |
56
+ | [cx](https://openqasm.com/language/standard_library.html#cx) | CX |
57
+ | [swap](https://openqasm.com/language/standard_library.html#swap) | SWAP |
58
+ | [h](https://openqasm.com/language/standard_library.html#h) | H |
59
+ | [s](https://openqasm.com/language/standard_library.html#s) | S |
60
+ | [x](https://openqasm.com/language/standard_library.html#x) | X |
61
+ | [y](https://openqasm.com/language/standard_library.html#y) | Y |
62
+ | [z](https://openqasm.com/language/standard_library.html#z) | Z |
63
+ | [id](https://openqasm.com/language/standard_library.html#id) | I |
64
+ | [rx](https://openqasm.com/language/standard_library.html#rx) | RX |
65
+ | [ry](https://openqasm.com/language/standard_library.html#ry) | RY |
66
+ | [rz](https://openqasm.com/language/standard_library.html#rz) | RZ |
67
+
68
+ ### Expressions
69
+
70
+ Expressions with arithmetic operators (`+`, `-`, `*`, `/`, `%`) are supported.
71
+ The constant `pi` (or `π`) is defined.
72
+
73
+ [Compile-time constants](https://openqasm.com/language/types.html#compile-time-constants)
74
+ can be defined and used in expressions.
75
+
76
+
@@ -0,0 +1,5 @@
1
+ """Graphix QASM parser."""
2
+
3
+ from graphix_qasm_parser.parser import OpenQASMParser
4
+
5
+ __all__ = ["OpenQASMParser"]
@@ -0,0 +1,464 @@
1
+ """Graphix OpenQASM parser."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from typing import TYPE_CHECKING
8
+
9
+ from antlr4 import ( # type: ignore[attr-defined]
10
+ CommonTokenStream,
11
+ FileStream,
12
+ InputStream,
13
+ ParserRuleContext,
14
+ )
15
+ from graphix import Circuit
16
+ from graphix.instruction import CCX, CNOT, RX, RY, RZ, RZZ, SWAP, H, I, S, X, Y, Z
17
+ from openqasm_parser import qasm3Lexer, qasm3Parser, qasm3ParserVisitor
18
+
19
+ # override introduced in Python 3.12
20
+ from typing_extensions import override
21
+
22
+ if TYPE_CHECKING:
23
+ from pathlib import Path
24
+
25
+ from graphix.instruction import Instruction
26
+
27
+
28
+ class OpenQASMParser:
29
+ """Graphix OpenQASM parser."""
30
+
31
+ def parse_stream(self, stream: InputStream) -> Circuit:
32
+ """Parse the OpenQASM circuit described in the given stream."""
33
+ lexer = qasm3Lexer(stream)
34
+ tokens = CommonTokenStream(lexer)
35
+ parser = qasm3Parser(tokens)
36
+ tree = parser.program() # type: ignore[no-untyped-call]
37
+ visitor = _CircuitVisitor(self)
38
+ tree.accept(visitor)
39
+ return Circuit(visitor.width, instr=visitor.instructions)
40
+
41
+ def parse_str(self, s: str) -> Circuit:
42
+ """Parse the OpenQASM circuit described in the given string."""
43
+ stream = InputStream(s)
44
+ return self.parse_stream(stream)
45
+
46
+ def parse_file(self, path: Path | str) -> Circuit:
47
+ """Parse the OpenQASM circuit described in the given file."""
48
+ stream = FileStream(str(path))
49
+ return self.parse_stream(stream)
50
+
51
+
52
+ @dataclass
53
+ class _Value:
54
+ ctx: ParserRuleContext | str # type: ignore[valid-type]
55
+
56
+ def __neg__(self) -> _Value:
57
+ return NotImplemented # type: ignore[no-any-return]
58
+
59
+ def __add__(self, other: object) -> _Value:
60
+ return NotImplemented
61
+
62
+ def __radd__(self, other: object) -> _Value:
63
+ return NotImplemented
64
+
65
+ def __sub__(self, other: object) -> _Value:
66
+ return NotImplemented
67
+
68
+ def __rsub__(self, other: object) -> _Value:
69
+ return NotImplemented
70
+
71
+ def __mul__(self, other: object) -> _Value:
72
+ return NotImplemented
73
+
74
+ def __rmul__(self, other: object) -> _Value:
75
+ return NotImplemented
76
+
77
+ def __truediv__(self, other: object) -> _Value:
78
+ return NotImplemented
79
+
80
+ def __rtruediv__(self, other: object) -> _Value:
81
+ return NotImplemented
82
+
83
+ def __mod__(self, other: object) -> _Value:
84
+ return NotImplemented
85
+
86
+ def __rmod__(self, other: object) -> _Value:
87
+ return NotImplemented
88
+
89
+ def __int__(self) -> int:
90
+ msg = "Not an integer value: {ctx.getText() if isinstance(ctx, ParserRuleContext) else ctx}"
91
+ raise TypeError(msg)
92
+
93
+ def __float__(self) -> float:
94
+ msg = "Not a floating-point value: {ctx.getText() if isinstance(ctx, ParserRuleContext) else ctx}"
95
+ raise TypeError(msg)
96
+
97
+
98
+ @dataclass
99
+ class _Int(_Value):
100
+ value: int
101
+
102
+ @override
103
+ def __neg__(self) -> _Value:
104
+ return _Int(self.ctx, -self.value)
105
+
106
+ @override
107
+ def __add__(self, other: object) -> _Value:
108
+ if isinstance(other, _Int):
109
+ return _Int(self.ctx, self.value + other.value)
110
+ return NotImplemented
111
+
112
+ @override
113
+ def __sub__(self, other: object) -> _Value:
114
+ if isinstance(other, _Int):
115
+ return _Int(self.ctx, self.value - other.value)
116
+ return NotImplemented
117
+
118
+ @override
119
+ def __mul__(self, other: object) -> _Value:
120
+ if isinstance(other, _Int):
121
+ return _Int(self.ctx, self.value * other.value)
122
+ return NotImplemented
123
+
124
+ @override
125
+ def __truediv__(self, other: object) -> _Value:
126
+ if isinstance(other, _Int):
127
+ result = self.value / other.value
128
+ if isinstance(result, int):
129
+ return _Int(self.ctx, result)
130
+ return _Float(self.ctx, result)
131
+ return NotImplemented
132
+
133
+ @override
134
+ def __mod__(self, other: object) -> _Value:
135
+ if isinstance(other, _Int):
136
+ return _Int(self.ctx, self.value % other.value)
137
+ return NotImplemented
138
+
139
+ @override
140
+ def __int__(self) -> int:
141
+ return self.value
142
+
143
+ @override
144
+ def __float__(self) -> float:
145
+ return float(self.value)
146
+
147
+
148
+ @dataclass
149
+ class _Float(_Value):
150
+ value: float
151
+
152
+ @override
153
+ def __neg__(self) -> _Value:
154
+ return _Float(self.ctx, -self.value)
155
+
156
+ @override
157
+ def __add__(self, other: object) -> _Value:
158
+ if isinstance(other, (_Int, _Float)):
159
+ return _Float(self.ctx, self.value + other.value)
160
+ return NotImplemented
161
+
162
+ @override
163
+ def __radd__(self, other: object) -> _Value:
164
+ if isinstance(other, _Int):
165
+ return _Float(self.ctx, other.value + self.value)
166
+ return NotImplemented
167
+
168
+ @override
169
+ def __sub__(self, other: object) -> _Value:
170
+ if isinstance(other, (_Int, _Float)):
171
+ return _Float(self.ctx, self.value - other.value)
172
+ return NotImplemented
173
+
174
+ @override
175
+ def __rsub__(self, other: object) -> _Value:
176
+ if isinstance(other, _Int):
177
+ return _Float(self.ctx, other.value - self.value)
178
+ return NotImplemented
179
+
180
+ @override
181
+ def __mul__(self, other: object) -> _Value:
182
+ if isinstance(other, (_Int, _Float)):
183
+ return _Float(self.ctx, self.value * other.value)
184
+ return NotImplemented
185
+
186
+ @override
187
+ def __rmul__(self, other: object) -> _Value:
188
+ if isinstance(other, _Int):
189
+ return _Float(self.ctx, other.value * self.value)
190
+ return NotImplemented
191
+
192
+ @override
193
+ def __truediv__(self, other: object) -> _Value:
194
+ if isinstance(other, (_Int, _Float)):
195
+ return _Float(self.ctx, self.value / other.value)
196
+ return NotImplemented
197
+
198
+ @override
199
+ def __rtruediv__(self, other: object) -> _Value:
200
+ if isinstance(other, _Int):
201
+ return _Float(self.ctx, other.value / self.value)
202
+ return NotImplemented
203
+
204
+ @override
205
+ def __mod__(self, other: object) -> _Value:
206
+ if isinstance(other, _Float):
207
+ return _Float(self.ctx, self.value % other.value)
208
+ return NotImplemented
209
+
210
+ @override
211
+ def __rmod__(self, other: object) -> _Value:
212
+ if isinstance(other, _Float):
213
+ return _Float(self.ctx, other.value % self.value)
214
+ return NotImplemented
215
+
216
+ @override
217
+ def __float__(self) -> float:
218
+ return self.value
219
+
220
+
221
+ @dataclass
222
+ class _Bit(_Value):
223
+ index: int
224
+
225
+
226
+ @dataclass
227
+ class _Qubit(_Value):
228
+ index: int
229
+
230
+
231
+ @dataclass
232
+ class _Array(_Value):
233
+ values: list[_Value]
234
+
235
+
236
+ class _CircuitVisitor(qasm3ParserVisitor):
237
+ parser: OpenQASMParser
238
+ width: int
239
+ instructions: list[Instruction]
240
+ env: dict[str, _Value]
241
+
242
+ def __init__(self, parser: OpenQASMParser) -> None:
243
+ self.parser = parser
244
+ self.width = 0
245
+ self.instructions = []
246
+ self.env = {
247
+ "pi": _Float("pi", math.pi),
248
+ "π": _Float("π", math.pi),
249
+ }
250
+
251
+ @override
252
+ def visitOldStyleDeclarationStatement(self, ctx: qasm3Parser.OldStyleDeclarationStatementContext) -> None:
253
+ decl_class: type[_Bit | _Qubit]
254
+ kind = ctx.getChild(0)
255
+ if kind.symbol.type == qasm3Parser.QREG:
256
+ decl_class = _Qubit
257
+ elif kind.symbol.type == qasm3Parser.CREG:
258
+ decl_class = _Bit
259
+ else:
260
+ msg = f"Unknown declaration statement kind: {kind}"
261
+ raise NotImplementedError(msg)
262
+ identifier = ctx.Identifier().getText() # type: ignore[no-untyped-call]
263
+ designator = ctx.designator() # type: ignore[no-untyped-call]
264
+ self.declare_registers(ctx, decl_class, identifier, designator)
265
+
266
+ @override
267
+ def visitQuantumDeclarationStatement(self, ctx: qasm3Parser.QuantumDeclarationStatementContext) -> None:
268
+ designator = ctx.qubitType().designator() # type: ignore[no-untyped-call]
269
+ identifier = ctx.Identifier().getText() # type: ignore[no-untyped-call]
270
+ self.declare_registers(ctx, _Qubit, identifier, designator)
271
+
272
+ @override
273
+ def visitConstDeclarationStatement(self, ctx: qasm3Parser.ConstDeclarationStatementContext) -> None:
274
+ identifier = ctx.Identifier().getText() # type: ignore[no-untyped-call]
275
+ value = ctx.declarationExpression() # type: ignore[no-untyped-call]
276
+ expr = self.evaluate_expression(value)
277
+ self.env[identifier] = expr
278
+
279
+ @override
280
+ def visitGateCallStatement(self, ctx: qasm3Parser.GateCallStatementContext) -> None: # noqa: C901, PLR0912
281
+ gate = ctx.Identifier().getText() # type: ignore[no-untyped-call]
282
+ operand_list = ctx.gateOperandList() # type: ignore[no-untyped-call]
283
+ operands = [
284
+ self.convert_qubit_index(operand_list.getChild(i)) for i in range(0, operand_list.getChildCount(), 2)
285
+ ]
286
+ if expr_list := ctx.expressionList(): # type: ignore[no-untyped-call]
287
+ exprs = [
288
+ float(self.evaluate_expression(expr_list.getChild(i))) for i in range(0, expr_list.getChildCount(), 2)
289
+ ]
290
+ else:
291
+ exprs = []
292
+ instruction: Instruction
293
+ if gate == "ccx":
294
+ # https://openqasm.com/language/standard_library.html#ccx
295
+ instruction = CCX(target=operands[2], controls=(operands[0], operands[1]))
296
+ elif gate == "crz":
297
+ # https://openqasm.com/language/standard_library.html#crz
298
+ instruction = RZZ(target=operands[1], control=operands[0], angle=exprs[0])
299
+ elif gate == "cx":
300
+ # https://openqasm.com/language/standard_library.html#cx
301
+ instruction = CNOT(target=operands[1], control=operands[0])
302
+ elif gate == "swap":
303
+ # https://openqasm.com/language/standard_library.html#swap
304
+ instruction = SWAP(targets=(operands[0], operands[1]))
305
+ elif gate == "h":
306
+ # https://openqasm.com/language/standard_library.html#h
307
+ instruction = H(target=operands[0])
308
+ elif gate == "s":
309
+ # https://openqasm.com/language/standard_library.html#s
310
+ instruction = S(target=operands[0])
311
+ elif gate == "x":
312
+ # https://openqasm.com/language/standard_library.html#x
313
+ instruction = X(target=operands[0])
314
+ elif gate == "y":
315
+ # https://openqasm.com/language/standard_library.html#y
316
+ instruction = Y(target=operands[0])
317
+ elif gate == "z":
318
+ # https://openqasm.com/language/standard_library.html#z
319
+ instruction = Z(target=operands[0])
320
+ elif gate == "id":
321
+ # https://openqasm.com/language/standard_library.html#id
322
+ instruction = I(target=operands[0])
323
+ elif gate == "rx":
324
+ # https://openqasm.com/language/standard_library.html#rx
325
+ instruction = RX(target=operands[0], angle=exprs[0])
326
+ elif gate == "ry":
327
+ # https://openqasm.com/language/standard_library.html#ry
328
+ instruction = RY(target=operands[0], angle=exprs[0])
329
+ elif gate == "rz":
330
+ # https://openqasm.com/language/standard_library.html#rz
331
+ instruction = RZ(target=operands[0], angle=exprs[0])
332
+ else:
333
+ msg = f"Unknown gate: {gate}"
334
+ raise NotImplementedError(msg)
335
+ self.instructions.append(instruction)
336
+
337
+ def declare_registers(
338
+ self,
339
+ ctx: ParserRuleContext, # type: ignore[valid-type]
340
+ decl_class: type[_Bit | _Qubit],
341
+ identifier: str,
342
+ designator: qasm3Parser.DesignatorContext | None,
343
+ ) -> None:
344
+ value: _Value
345
+ if designator:
346
+ expression = designator.expression() # type: ignore[no-untyped-call]
347
+ count = int(self.evaluate_expression(expression))
348
+ value = _Array(ctx, [decl_class(ctx, self.width + i) for i in range(count)])
349
+ self.width += count
350
+ else:
351
+ value = decl_class(ctx, self.width)
352
+ self.width += 1
353
+ self.env[identifier] = value
354
+
355
+ def convert_qubit_index(self, operand: qasm3Parser.GateOperandContext) -> int:
356
+ value = self.evaluate_operand(operand)
357
+ if isinstance(value, _Qubit):
358
+ return value.index
359
+ msg = f"Qubit expected: {operand}"
360
+ raise ValueError(msg)
361
+
362
+ def evaluate_operand(self, operand: qasm3Parser.GateOperandContext) -> _Value:
363
+ child = operand.getChild(0)
364
+ if child.getRuleIndex() == qasm3Parser.RULE_indexedIdentifier:
365
+ identifier = child.Identifier().getText()
366
+ value = self.env.get(identifier)
367
+ if value is None:
368
+ msg = f"name {identifier} is not defined"
369
+ raise NameError(msg)
370
+ for operator in child.indexOperator():
371
+ if not isinstance(value, _Array):
372
+ msg = f"Array expected: {identifier}"
373
+ raise TypeError(msg)
374
+ index = int(self.evaluate_expression(operator.expression(0)))
375
+ if index < 0:
376
+ msg = f"Negative index: {identifier}"
377
+ raise IndexError(msg)
378
+ if index >= len(value.values):
379
+ msg = f"Index out of bounds: {identifier} has length {len(value.values)}"
380
+ raise IndexError(msg)
381
+ value = value.values[index]
382
+ return value
383
+ msg = f"Unknown operand: {operand}"
384
+ raise NotImplementedError(msg)
385
+
386
+ def evaluate_expression(self, expr: qasm3Parser.ExpressionContext) -> _Value:
387
+ return _ExpressionVisitor(self).parse(expr)
388
+
389
+
390
+ class _ExpressionVisitor(qasm3ParserVisitor):
391
+ circuit: _CircuitVisitor
392
+
393
+ def __init__(self, circuit: _CircuitVisitor) -> None:
394
+ self.circuit = circuit
395
+
396
+ def parse(self, expr: qasm3Parser.ExpressionContext) -> _Value:
397
+ value: _Value | None = expr.accept(self)
398
+ if value is None:
399
+ msg = f"Cannot parse value: {expr.getText()}"
400
+ raise NotImplementedError(msg)
401
+ return value
402
+
403
+ @override
404
+ def visitParenthesisExpression(self, ctx: qasm3Parser.ParenthesisExpressionContext) -> _Value:
405
+ expr: qasm3Parser.ExpressionContext = ctx.expression() # type: ignore[no-untyped-call]
406
+ return self.parse(expr)
407
+
408
+ @override
409
+ def visitUnaryExpression(self, ctx: qasm3Parser.UnaryExpressionContext) -> _Value:
410
+ operand_expr: qasm3Parser.ExpressionContext = ctx.expression() # type: ignore[no-untyped-call]
411
+ operand = self.parse(operand_expr)
412
+ operator = ctx.getChild(0).symbol.type
413
+ if operator == qasm3Parser.MINUS:
414
+ result = -operand
415
+ result.ctx = ctx
416
+ return result
417
+ msg = f"Unknown operator: {ctx.getChild(0).symbol.text}"
418
+ raise NotImplementedError(msg)
419
+
420
+ @override
421
+ def visitAdditiveExpression(self, ctx: qasm3Parser.AdditiveExpressionContext) -> _Value:
422
+ return self.parse_binary_operator(ctx)
423
+
424
+ @override
425
+ def visitMultiplicativeExpression(self, ctx: qasm3Parser.MultiplicativeExpressionContext) -> _Value:
426
+ return self.parse_binary_operator(ctx)
427
+
428
+ @override
429
+ def visitLiteralExpression(self, ctx: qasm3Parser.LiteralExpressionContext) -> _Value:
430
+ literal = ctx.getChild(0)
431
+ if literal.symbol.type == qasm3Parser.DecimalIntegerLiteral:
432
+ return _Int(ctx, int(literal.symbol.text))
433
+ if literal.symbol.type == qasm3Parser.FloatLiteral:
434
+ return _Float(ctx, float(literal.symbol.text))
435
+ if literal.symbol.type == qasm3Parser.Identifier:
436
+ identifier = literal.symbol.text
437
+ if value := self.circuit.env.get(identifier):
438
+ return value
439
+ msg = f"Unknown literal: {literal.symbol.text}"
440
+ raise NotImplementedError(msg)
441
+
442
+ def parse_binary_operator(
443
+ self, ctx: qasm3Parser.AdditiveExpressionContext | qasm3Parser.MultiplicativeExpressionContext
444
+ ) -> _Value:
445
+ lhs_expr: qasm3Parser.ExpressionContext = ctx.getChild(0)
446
+ rhs_expr: qasm3Parser.ExpressionContext = ctx.getChild(2)
447
+ lhs = self.parse(lhs_expr)
448
+ rhs = self.parse(rhs_expr)
449
+ operator = ctx.getChild(1).symbol.type
450
+ if operator == qasm3Parser.ASTERISK:
451
+ result = lhs * rhs
452
+ elif operator == qasm3Parser.SLASH:
453
+ result = lhs / rhs
454
+ elif operator == qasm3Parser.PERCENT:
455
+ result = lhs % rhs
456
+ elif operator == qasm3Parser.PLUS:
457
+ result = lhs + rhs
458
+ elif operator == qasm3Parser.MINUS:
459
+ result = lhs - rhs
460
+ else:
461
+ msg = f"Unknown operator: {ctx.getChild(1).symbol.text}"
462
+ raise NotImplementedError(msg)
463
+ result.ctx = ctx
464
+ return result
File without changes
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: graphix-qasm-parser
3
+ Version: 0.1.0
4
+ Author-email: Thierry Martinez <Thierry.Martinez@inria.fr>
5
+ Maintainer-email: Thierry Martinez <Thierry.Martinez@inria.fr>
6
+ License-File: LICENSE
7
+ Requires-Dist: graphix>=0.3.1
8
+ Requires-Dist: openqasm-parser>=3.1.0
9
+ Provides-Extra: dev
10
+ Requires-Dist: mypy==1.17.0; extra == "dev"
11
+ Requires-Dist: pyright; extra == "dev"
12
+ Requires-Dist: ruff==0.12.5; extra == "dev"
13
+ Requires-Dist: nox==2025.5.1; extra == "dev"
14
+ Requires-Dist: pytest; extra == "dev"
15
+ Dynamic: license-file
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ requirements-dev.txt
5
+ requirements.txt
6
+ graphix_qasm_parser/__init__.py
7
+ graphix_qasm_parser/_version.py
8
+ graphix_qasm_parser/parser.py
9
+ graphix_qasm_parser/py.typed
10
+ graphix_qasm_parser.egg-info/PKG-INFO
11
+ graphix_qasm_parser.egg-info/SOURCES.txt
12
+ graphix_qasm_parser.egg-info/dependency_links.txt
13
+ graphix_qasm_parser.egg-info/requires.txt
14
+ graphix_qasm_parser.egg-info/top_level.txt
15
+ tests/test_parser.py
@@ -0,0 +1,9 @@
1
+ graphix>=0.3.1
2
+ openqasm-parser>=3.1.0
3
+
4
+ [dev]
5
+ mypy==1.17.0
6
+ pyright
7
+ ruff==0.12.5
8
+ nox==2025.5.1
9
+ pytest
@@ -0,0 +1 @@
1
+ graphix_qasm_parser
@@ -0,0 +1,66 @@
1
+ [project]
2
+ name = "graphix-qasm-parser"
3
+ authors = [
4
+ { name = "Thierry Martinez", email = "Thierry.Martinez@inria.fr" },
5
+ ]
6
+ maintainers = [
7
+ { name = "Thierry Martinez", email = "Thierry.Martinez@inria.fr" },
8
+ ]
9
+ license-files = ["LICENSE"]
10
+ version = "0.1.0"
11
+ dynamic = ["dependencies", "optional-dependencies"]
12
+
13
+ [tool.setuptools.dynamic]
14
+ dependencies = { file = ["requirements.txt"] }
15
+
16
+ [tool.setuptools.dynamic.optional-dependencies]
17
+ dev = { file = ["requirements-dev.txt"] }
18
+
19
+ [tool.ruff]
20
+ line-length = 120
21
+
22
+ [tool.ruff.lint]
23
+ select = ["ALL"]
24
+ # Allow "α" (U+03B1 GREEK SMALL LETTER ALPHA) which could be confused for "a"
25
+ # Allow "×" (U+00D7 MULTIPLICATION SIGN) which could be confused for "x"
26
+ allowed-confusables = ["α", "×"]
27
+ extend-ignore = [
28
+ "D203", # `incorrect-blank-line-before-class` (D203) and `no-blank-line-before-class` (D211) are incompatible.
29
+ "D212", # `multi-line-summary-first-line` (D212) and `multi-line-summary-second-line` (D213) are incompatible.
30
+ "COM812", # The following rule may cause conflicts when used with the formatter: `COM812`.
31
+ "PLR2004", # Magic value used in comparison
32
+ "E501", # Line too long
33
+ ]
34
+
35
+ [tool.ruff.lint.per-file-ignores]
36
+ "tests/*.py" = [
37
+ "S101", # Use of `assert`
38
+ ]
39
+
40
+ [tool.ruff.format]
41
+ docstring-code-format = true
42
+
43
+ [tool.mypy]
44
+ # Keep in sync with pyright
45
+ files = ["*.py", "graphix_qasm_parser"]
46
+ # For antlr4
47
+ ignore_missing_imports = true
48
+ follow_untyped_imports = true
49
+ strict = true
50
+
51
+ [tool.pyright]
52
+ # Keep in sync with pyright
53
+ files = ["*.py", "graphix_qasm_parser"]
54
+ typeCheckingMode = "strict"
55
+ # For antlr4
56
+ reportMissingImports = "none"
57
+ reportMissingTypeStubs = "none"
58
+ reportUnknownVariableType = "none"
59
+ reportUnknownMemberType = "none"
60
+ reportUnknownParameterType = "none"
61
+ reportUnknownArgumentType = "none"
62
+ # reportUnknownArgumentType = "information"
63
+ reportUnknownLambdaType = "information"
64
+ #reportUnknownMemberType = "information"
65
+ # reportUnknownParameterType = "information"
66
+ # reportUnknownVariableType = "information"
@@ -0,0 +1,8 @@
1
+ # Lint/format
2
+ mypy==1.17.0
3
+ pyright
4
+ ruff==0.12.5
5
+
6
+ # Tests
7
+ nox==2025.5.1
8
+ pytest
@@ -0,0 +1,2 @@
1
+ graphix>=0.3.1
2
+ openqasm-parser>=3.1.0
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,200 @@
1
+ """Tests for Graphix QASM parser."""
2
+
3
+ import math
4
+
5
+ import pytest
6
+ from graphix.instruction import CCX, CNOT, RX, RY, RZ, RZZ, SWAP, H, S, X, Y, Z
7
+
8
+ from graphix_qasm_parser import OpenQASMParser
9
+
10
+
11
+ def test_parse_simple_circuit() -> None:
12
+ """Test parse simple circuit."""
13
+ s = """
14
+ include "qelib1.inc";
15
+ qubit q;
16
+ rz(5*pi/4) q;
17
+ """
18
+ parser = OpenQASMParser()
19
+ circuit = parser.parse_str(s)
20
+ assert circuit.width == 1
21
+ assert len(circuit.instruction) == 1
22
+ instruction = circuit.instruction[0]
23
+ assert isinstance(instruction, RZ)
24
+ assert isinstance(instruction.angle, float)
25
+ assert math.isclose(instruction.angle, 5 * math.pi / 4)
26
+
27
+
28
+ def test_parse_simple_circuit_old_syntax() -> None:
29
+ """Test parse simple circuit."""
30
+ s = """
31
+ include "qelib1.inc";
32
+ qreg q;
33
+ rz(5*pi/4) q;
34
+ """
35
+ parser = OpenQASMParser()
36
+ circuit = parser.parse_str(s)
37
+ assert circuit.width == 1
38
+ assert len(circuit.instruction) == 1
39
+ instruction = circuit.instruction[0]
40
+ assert isinstance(instruction, RZ)
41
+ assert isinstance(instruction.angle, float)
42
+ assert math.isclose(instruction.angle, 5 * math.pi / 4)
43
+
44
+
45
+ def test_parse_all_instructions() -> None: # noqa: PLR0915
46
+ """Test parse all instructions."""
47
+ s = """
48
+ include "qelib1.inc";
49
+ qubit[3] q;
50
+ ccx q[0], q[1], q[2];
51
+ crz(pi/3) q[0], q[1];
52
+ cx q[0], q[1];
53
+ swap q[0], q[1];
54
+ h q[0];
55
+ s q[0];
56
+ x q[0];
57
+ y q[0];
58
+ z q[0];
59
+ rx(pi/4) q[0];
60
+ ry(pi/4) q[0];
61
+ rz(pi/4) q[0];
62
+ """
63
+ parser = OpenQASMParser()
64
+ circuit = parser.parse_str(s)
65
+ assert circuit.width == 3
66
+ iterator = iter(circuit.instruction)
67
+ instruction = next(iterator)
68
+ assert isinstance(instruction, CCX)
69
+ assert instruction.target == 2
70
+ assert instruction.controls == (0, 1)
71
+ instruction = next(iterator)
72
+ assert isinstance(instruction, RZZ)
73
+ assert instruction.target == 1
74
+ assert instruction.control == 0
75
+ assert isinstance(instruction.angle, float)
76
+ assert math.isclose(instruction.angle, math.pi / 3)
77
+ instruction = next(iterator)
78
+ assert isinstance(instruction, CNOT)
79
+ assert instruction.target == 1
80
+ assert instruction.control == 0
81
+ instruction = next(iterator)
82
+ assert isinstance(instruction, SWAP)
83
+ assert instruction.targets == (0, 1)
84
+ instruction = next(iterator)
85
+ assert isinstance(instruction, H)
86
+ assert instruction.target == 0
87
+ instruction = next(iterator)
88
+ assert isinstance(instruction, S)
89
+ assert instruction.target == 0
90
+ instruction = next(iterator)
91
+ assert isinstance(instruction, X)
92
+ assert instruction.target == 0
93
+ instruction = next(iterator)
94
+ assert isinstance(instruction, Y)
95
+ assert instruction.target == 0
96
+ instruction = next(iterator)
97
+ assert isinstance(instruction, Z)
98
+ assert instruction.target == 0
99
+ instruction = next(iterator)
100
+ assert isinstance(instruction, RX)
101
+ assert instruction.target == 0
102
+ assert isinstance(instruction.angle, float)
103
+ assert math.isclose(instruction.angle, math.pi / 4)
104
+ instruction = next(iterator)
105
+ assert isinstance(instruction, RY)
106
+ assert instruction.target == 0
107
+ assert isinstance(instruction.angle, float)
108
+ assert math.isclose(instruction.angle, math.pi / 4)
109
+ instruction = next(iterator)
110
+ assert isinstance(instruction, RZ)
111
+ assert instruction.target == 0
112
+ assert isinstance(instruction.angle, float)
113
+ assert math.isclose(instruction.angle, math.pi / 4)
114
+ with pytest.raises(StopIteration):
115
+ next(iterator)
116
+
117
+
118
+ def test_parse_all_expressions() -> None:
119
+ """Test parse all expressions."""
120
+ s = """
121
+ include "qelib1.inc";
122
+ qubit q;
123
+ rz((1)) q;
124
+ rz(1.5) q;
125
+ rz(- 1) q;
126
+ rz(1 + 2) q;
127
+ rz(1 - 2) q;
128
+ rz(1 * 2) q;
129
+ rz(1 / 2) q;
130
+ rz(1 - (2 + 3)) q;
131
+ rz(pi) q;
132
+ rz(π) q;
133
+ """
134
+ parser = OpenQASMParser()
135
+ circuit = parser.parse_str(s)
136
+ assert circuit.width == 1
137
+ iterator = iter(circuit.instruction)
138
+ instruction = next(iterator)
139
+ assert isinstance(instruction, RZ)
140
+ assert isinstance(instruction.angle, float)
141
+ assert math.isclose(instruction.angle, 1)
142
+ instruction = next(iterator)
143
+ assert isinstance(instruction, RZ)
144
+ assert isinstance(instruction.angle, float)
145
+ assert math.isclose(instruction.angle, 1.5)
146
+ instruction = next(iterator)
147
+ assert isinstance(instruction, RZ)
148
+ assert isinstance(instruction.angle, float)
149
+ assert math.isclose(instruction.angle, -1)
150
+ instruction = next(iterator)
151
+ assert isinstance(instruction, RZ)
152
+ assert isinstance(instruction.angle, float)
153
+ assert math.isclose(instruction.angle, 1 + 2)
154
+ instruction = next(iterator)
155
+ assert isinstance(instruction, RZ)
156
+ assert isinstance(instruction.angle, float)
157
+ assert math.isclose(instruction.angle, 1 - 2)
158
+ instruction = next(iterator)
159
+ assert isinstance(instruction, RZ)
160
+ assert isinstance(instruction.angle, float)
161
+ assert math.isclose(instruction.angle, 1 * 2)
162
+ instruction = next(iterator)
163
+ assert isinstance(instruction, RZ)
164
+ assert isinstance(instruction.angle, float)
165
+ assert math.isclose(instruction.angle, 1 / 2)
166
+ instruction = next(iterator)
167
+ assert isinstance(instruction, RZ)
168
+ assert isinstance(instruction.angle, float)
169
+ assert math.isclose(instruction.angle, 1 - (2 + 3))
170
+ instruction = next(iterator)
171
+ assert isinstance(instruction, RZ)
172
+ assert isinstance(instruction.angle, float)
173
+ assert math.isclose(instruction.angle, math.pi)
174
+ instruction = next(iterator)
175
+ assert isinstance(instruction, RZ)
176
+ assert isinstance(instruction.angle, float)
177
+ assert math.isclose(instruction.angle, math.pi)
178
+ with pytest.raises(StopIteration):
179
+ next(iterator)
180
+
181
+
182
+ def test_const_declarations() -> None:
183
+ """Test constant declarations."""
184
+ s = """
185
+ include "qelib1.inc";
186
+ const int SIZE = 1;
187
+ const angle alpha = pi / 4;
188
+ qubit[SIZE] q;
189
+ rz(alpha) q[0];
190
+ """
191
+ parser = OpenQASMParser()
192
+ circuit = parser.parse_str(s)
193
+ assert circuit.width == 1
194
+ iterator = iter(circuit.instruction)
195
+ instruction = next(iterator)
196
+ assert isinstance(instruction, RZ)
197
+ assert isinstance(instruction.angle, float)
198
+ assert math.isclose(instruction.angle, math.pi / 4)
199
+ with pytest.raises(StopIteration):
200
+ next(iterator)