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'")