OpenQASM 3 Python AST

1.0.1 · active · verified Wed Apr 15

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

Install

Imports

Quickstart

This example demonstrates how to parse a simple OpenQASM 3 program string into its Abstract Syntax Tree representation using the `openqasm3.parser.parse` function. The resulting `Program` object can then be inspected or traversed for further processing.

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

view raw JSON →