From 83caaa63dfedc443b8514db0060551720dd2c818 Mon Sep 17 00:00:00 2001 From: Jake Lishman Date: Mon, 12 Aug 2024 13:22:50 +0100 Subject: [PATCH] Improve error message on bad OpenQASM 3 `basis_gates` argument 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. --- qiskit/qasm3/exporter.py | 8 +++++++- .../notes/qasm3-basis-gates-keyword-c5998bff1e178715.yaml | 5 +++++ test/python/qasm3/test_export.py | 8 ++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 releasenotes/notes/qasm3-basis-gates-keyword-c5998bff1e178715.yaml diff --git a/qiskit/qasm3/exporter.py b/qiskit/qasm3/exporter.py index 098ab8578d48..561e59a72242 100644 --- a/qiskit/qasm3/exporter.py +++ b/qiskit/qasm3/exporter.py @@ -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())) diff --git a/releasenotes/notes/qasm3-basis-gates-keyword-c5998bff1e178715.yaml b/releasenotes/notes/qasm3-basis-gates-keyword-c5998bff1e178715.yaml new file mode 100644 index 000000000000..82347fd920fc --- /dev/null +++ b/releasenotes/notes/qasm3-basis-gates-keyword-c5998bff1e178715.yaml @@ -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. diff --git a/test/python/qasm3/test_export.py b/test/python/qasm3/test_export.py index 703b5f8cac12..868846925753 100644 --- a/test/python/qasm3/test_export.py +++ b/test/python/qasm3/test_export.py @@ -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'")