Repository navigation
Description
Environment
- PyQASM version: 1.0.4 (
main@ 5dcae69) - Python version: 3.11
- Operating system: macOS
What happened?
pyqasm detects direct gate self-recursion and raises a clean ValidationError, but an indirect cycle between two gate definitions is not detected and instead exhausts the Python stack.
import pyqasm
# direct — handled correctly
pyqasm.loads('''OPENQASM 2.0;
include "qelib1.inc";
gate a(t) q { a(t) q; }
qreg q[1];
a(0.5) q[0];
''').validate()
# ValidationError: Recursive definitions not allowed for gate 'a'
# indirect — stack blowout
pyqasm.loads('''OPENQASM 2.0;
include "qelib1.inc";
gate a(t) q { b(t) q; }
gate b(t) q { a(t) q; }
qreg q[1];
a(0.5) q[0];
''').validate()
# RecursionError: maximum recursion depth exceeded while calling a Python objectFor contrast, a forward reference to a gate that is never defined is reported correctly:
ValidationError: Unsupported / undeclared QASM operation: b
So the three cases behave as: direct cycle → good error; undefined gate → good error; indirect cycle → RecursionError.
Cause
The guard at visitor.py:1271 compares a single level:
if isinstance(gate_op, qasm3_ast.QuantumGate) and gate_op.name.name == gate_name:
raise_qasm3_error(
f"Recursive definitions not allowed for gate '{gate_name}'",
...It only catches a body that references its own name. A cycle of length ≥ 2 passes the check and recurses through gate expansion until the interpreter's stack limit is reached.
Expected behaviour
A ValidationError identifying the cycle, in the same shape as the existing direct-recursion message — ideally naming the path, e.g. Recursive definitions not allowed for gate 'a' (a -> b -> a). Tracking the expansion chain and checking membership rather than comparing one name would cover both cases with the same code.
Why this came up
Not synthetic. Quantinuum's hqslib1.inc declares its primitives as opaque (see #54) and then defines U and CX in terms of those primitives. The obvious way to work around #54 — give the opaque primitives real gate bodies — creates a mutual cycle with those definitions, and the result is a bare RecursionError with no indication of which gates are involved. It took two attempts to work out what was cycling. Anyone attempting to fix #54 will very likely land here first.
Possibly related: #256, though that concerns OpenQASM 3 def subroutine recursion failing with a scoping/aliasing error, which is a different code path and a different failure mode — recursion is legal there, whereas a cyclic gate definition is not.
Activity
fix: detect gate definition cycles of any length, not just self-calls
fix: detect gate definition cycles of any length, not just self-calls
fix: detect gate definition cycles of any length, not just self-calls (…
fix: nested external gate depth, and gate definition cycles of any le…