Skip to content

Commit

Permalink
Improve error message on bad OpenQASM 3 basis_gates argument (#12945)
Browse files Browse the repository at this point in the history
If the user requests a basis-gate name that cannot be used (like a
keyword), there is nothing sensible we can output for a circuit that
contains one of those operations.  The exporter was already correctly
erroring in these cases, but the error message was quite opaque.
  • Loading branch information
jakelishman committed Aug 12, 2024
1 parent b1e7ffe commit fb9c0db
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
8 changes: 7 additions & 1 deletion qiskit/qasm3/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,7 +626,13 @@ def build_program(self):
if builtin in _BUILTIN_GATES:
# It's built into the langauge; we don't need to re-add it.
continue
self.symbols.register_gate_without_definition(builtin, None)
try:
self.symbols.register_gate_without_definition(builtin, None)
except QASM3ExporterError as exc:
raise QASM3ExporterError(
f"Cannot use '{builtin}' as a basis gate for the reason in the prior exception."
" Consider renaming the gate if needed, or omitting this basis gate if not."
) from exc

header = ast.Header(ast.Version("3.0"), list(self.build_includes()))

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
fixes:
- |
The OpenQASM 3 exporter will now correctly error when asked to use a keyword or other invalid
identifier as a "basis gate", as it has no way of putting out correct output in these cases.
8 changes: 8 additions & 0 deletions test/python/qasm3/test_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -2699,3 +2699,11 @@ def test_disallow_export_of_inner_scope(self):
QASM3ExporterError, "cannot export an inner scope.*as a top-level program"
):
dumps(qc)

def test_no_basis_gate_with_keyword(self):
"""Test that keyword cannot be used as a basis gate."""
qc = QuantumCircuit()
with self.assertRaisesRegex(QASM3ExporterError, "Cannot use 'reset' as a basis gate") as cm:
dumps(qc, basis_gates=["U", "reset"])
self.assertIsInstance(cm.exception.__cause__, QASM3ExporterError)
self.assertRegex(cm.exception.__cause__.message, "cannot use the keyword 'reset'")

0 comments on commit fb9c0db

Please sign in to comment.