OpenQASM 3 Python AST
The `openqasm3` library provides a reference Python implementation of the OpenQASM 3 Abstract Syntax Tree (AST). It enables parsing OpenQASM 3 programs into an AST and offers tools for manipulating this AST, facilitating the development of OpenQASM 3 compiler passes and analysis tools. The library, currently at version 1.0.1, actively supports the OpenQASM 3.1.0 specification, with releases often coinciding with updates to the OpenQASM specification.
Warnings
- breaking OpenQASM 3.0 introduced significant breaking changes compared to OpenQASM 2.0, including new keywords, classical control flow, explicit timing, and gate modifiers. This library specifically targets OpenQASM 3.x and is not compatible with OpenQASM 2.0 syntax.
- gotcha The `openqasm3` package relies on `antlr4-python3-runtime` for parsing. Compatibility is maintained across minor versions of ANTLR where possible through a dynamic import system. However, specific minor version mismatches (e.g., using `antlr4-python3-runtime==4.10.x` with `openqasm3` built for `4.11.x`) can lead to parsing errors or runtime issues.
- deprecated The `qreg` and `creg` keywords, fundamental in OpenQASM 2.0 for declaring quantum and classical registers, are not explicitly supported in the OpenQASM 3 specification and may cause issues or be fully removed in future specification versions. OpenQASM 3 primarily uses `qubit[N] q;` and `bit[N] c;`.
- gotcha The `openqasm3` library serves as a *reference AST* and parser for OpenQASM 3. It is not a full quantum compiler, simulator, or execution environment. Its primary purpose is to provide an in-memory representation for developing compiler passes and static analysis tools.
- breaking The API of the `openqasm3` Python package, including the AST structure, is explicitly stated to be in early development and subject to change in backwards-incompatible ways, mirroring the ongoing evolution of the OpenQASM 3 language itself.
Install
-
pip install openqasm3 -
pip install openqasm3[parser]
Imports
- parse
import openqasm3.parser.parse
from openqasm3.parser import parse
- Program
import openqasm3.ast.Program
from openqasm3.ast import Program
Quickstart
from openqasm3 import parser
from openqasm3 import ast # For type hinting or direct AST node creation
qasm_code = '''
OPENQASM 3;
qubit q;
h q;
measure q -> bit b;
'''
# Parse the OpenQASM 3 string into an AST Program object
program_ast = parser.parse(qasm_code)
# The __str__ method of the Program object provides a basic representation
print(program_ast)
# You can also iterate through the statements
print("\nStatements in AST:")
for statement in program_ast.statements:
print(f"- {type(statement).__name__}: {statement}")