Reference OpenQASM AST in Python - contains the reference abstract syntax tree (AST) for representing OpenQASM 3 programs, tools to parse text into this AST, and tools to manipulate the AST
—
Complete abstract syntax tree representing all OpenQASM 3 language constructs including quantum gates, classical code, control flow, type system, and calibration blocks. The AST provides a structured representation that enables systematic analysis and manipulation of OpenQASM 3 programs.
Foundational classes that define the structure and behavior of all AST nodes.
@dataclass
class QASMNode:
"""Base class for all OpenQASM 3 nodes"""
span: Optional[Span] = field(init=False, default=None, compare=False)
@dataclass
class Statement(QASMNode):
"""A statement: anything that can appear on its own line"""
annotations: List[Annotation] = field(init=False, default_factory=list)
class Expression(QASMNode):
"""Base class for anything that returns a value"""
pass
class QuantumStatement(Statement):
"""Base class for statements that may appear inside a gate declaration"""
pass
class ClassicalType(QASMNode):
"""Base class for classical types"""
passTop-level program representation and structural elements.
@dataclass
class Program(QASMNode):
"""An entire OpenQASM 3 program represented by a list of top level statements"""
statements: List[Union[Statement, Pragma]]
version: Optional[str] = None
@dataclass
class CompoundStatement(Statement):
"""A sequence of statements enclosed within an anonymous scope block"""
statements: List[Statement]
@dataclass
class Annotation(QASMNode):
"""An annotation applied to a statement"""
keyword: str
command: Optional[str] = None
@dataclass
class Pragma(QASMNode):
"""Pragma directive"""
command: strStatements that declare variables, qubits, gates, and other program elements.
@dataclass
class QubitDeclaration(Statement):
"""Global qubit declaration (e.g., qubit q; or qubit[4] q;)"""
qubit: Identifier
size: Optional[Expression] = None
@dataclass
class ClassicalDeclaration(Statement):
"""Classical variable declaration"""
type: ClassicalType
identifier: Identifier
init_expression: Optional[Union[Expression, QuantumMeasurement]] = None
@dataclass
class ConstantDeclaration(Statement):
"""Constant declaration"""
type: ClassicalType
identifier: Identifier
init_expression: Expression
@dataclass
class IODeclaration(Statement):
"""Input/output variable declaration"""
io_identifier: IOKeyword
type: ClassicalType
identifier: Identifier
@dataclass
class ExternDeclaration(Statement):
"""External function declaration"""
name: Identifier
arguments: List[ExternArgument]
return_type: Optional[ClassicalType] = NoneStatements specific to quantum operations and gate definitions.
@dataclass
class QuantumGateDefinition(Statement):
"""Define a new quantum gate"""
name: Identifier
arguments: List[Identifier]
qubits: List[Identifier]
body: List[QuantumStatement]
@dataclass
class QuantumGate(QuantumStatement):
"""Invoking a quantum gate"""
modifiers: List[QuantumGateModifier]
name: Identifier
arguments: List[Expression]
qubits: List[Union[IndexedIdentifier, Identifier]]
duration: Optional[Expression] = None
@dataclass
class QuantumPhase(QuantumStatement):
"""Quantum phase instruction"""
modifiers: List[QuantumGateModifier]
argument: Expression
qubits: List[Union[IndexedIdentifier, Identifier]]
@dataclass
class QuantumBarrier(QuantumStatement):
"""Quantum barrier instruction"""
qubits: List[Expression]
@dataclass
class QuantumReset(QuantumStatement):
"""Reset instruction"""
qubits: Union[IndexedIdentifier, Identifier]
@dataclass
class QuantumMeasurement(QASMNode):
"""Quantum measurement instruction"""
qubit: Union[IndexedIdentifier, Identifier]
@dataclass
class QuantumMeasurementStatement(Statement):
"""Stand-alone quantum measurement statement"""
measure: QuantumMeasurement
target: Optional[Union[IndexedIdentifier, Identifier]] = NoneStatements for classical and quantum control flow including loops and conditionals.
@dataclass
class BranchingStatement(Statement):
"""Branch (if) statement"""
condition: Expression
if_block: List[Statement]
else_block: List[Statement]
@dataclass
class WhileLoop(Statement):
"""While loop statement"""
while_condition: Expression
block: List[Statement]
@dataclass
class ForInLoop(Statement):
"""For-in loop statement"""
type: ClassicalType
identifier: Identifier
set_declaration: Union[RangeDefinition, DiscreteSet, Expression]
block: List[Statement]
@dataclass
class SwitchStatement(Statement):
"""Switch-case statement"""
target: Expression
cases: List[Tuple[List[Expression], CompoundStatement]]
default: Optional[CompoundStatement] = None
class BreakStatement(Statement):
"""Break statement"""
pass
class ContinueStatement(Statement):
"""Continue statement"""
pass
class EndStatement(Statement):
"""End statement"""
pass
@dataclass
class ReturnStatement(Statement):
"""Classical or quantum return statement"""
expression: Optional[Union[Expression, QuantumMeasurement]] = NoneDefinitions for classical subroutines and their arguments.
@dataclass
class SubroutineDefinition(Statement):
"""Subroutine definition"""
name: Identifier
arguments: List[Union[ClassicalArgument, QuantumArgument]]
body: List[Statement]
return_type: Optional[ClassicalType] = None
@dataclass
class ClassicalArgument(QASMNode):
"""Classical argument for gate or subroutine declarations"""
type: ClassicalType
name: Identifier
access: Optional[AccessControl] = None
@dataclass
class QuantumArgument(QASMNode):
"""Quantum argument for subroutine declarations"""
name: Identifier
size: Optional[Expression] = None
@dataclass
class ExternArgument(QASMNode):
"""Classical argument for extern declarations"""
type: ClassicalType
access: Optional[AccessControl] = NoneAll expression types including literals, operations, and function calls.
@dataclass
class Identifier(Expression):
"""An identifier"""
name: str
@dataclass
class IndexedIdentifier(QASMNode):
"""Identifier with index operators for use as lvalue"""
name: Identifier
indices: List[IndexElement]
# Literal expressions
@dataclass
class IntegerLiteral(Expression):
"""Integer literal"""
value: int
@dataclass
class FloatLiteral(Expression):
"""Real number literal"""
value: float
@dataclass
class ImaginaryLiteral(Expression):
"""Imaginary number literal (e.g., 1.1im)"""
value: float
@dataclass
class BooleanLiteral(Expression):
"""Boolean literal (true or false)"""
value: bool
@dataclass
class BitstringLiteral(Expression):
"""Literal bitstring value with numerical value and width"""
value: int
width: int
@dataclass
class DurationLiteral(Expression):
"""Duration literal (e.g., 1.0ns)"""
value: float
unit: TimeUnit
@dataclass
class ArrayLiteral(Expression):
"""Array literal for initializing declared arrays"""
values: List[Expression]
# Operation expressions
@dataclass
class UnaryExpression(Expression):
"""Unary expression (e.g., ~b, !bool, -i)"""
op: UnaryOperator
expression: Expression
@dataclass
class BinaryExpression(Expression):
"""Binary expression (e.g., q1 || q2)"""
op: BinaryOperator
lhs: Expression
rhs: Expression
@dataclass
class FunctionCall(Expression):
"""Function call expression"""
name: Identifier
arguments: List[Expression]
@dataclass
class Cast(Expression):
"""Type cast expression"""
type: ClassicalType
argument: Expression
@dataclass
class IndexExpression(Expression):
"""Index expression (e.g., q[1])"""
collection: Expression
index: IndexElement
@dataclass
class Concatenation(Expression):
"""Concatenation of two registers (e.g., a ++ b)"""
lhs: Expression
rhs: Expression
@dataclass
class DurationOf(Expression):
"""Duration of a block of statements"""
target: List[Statement]
@dataclass
class SizeOf(Expression):
"""Size of an array's dimensions"""
target: Expression
index: Optional[Expression] = NoneType system for classical variables and function parameters.
# Basic scalar types
@dataclass
class IntType(ClassicalType):
"""Signed integer type with optional precision (e.g., int[8])"""
size: Optional[Expression] = None
@dataclass
class UintType(ClassicalType):
"""Unsigned integer type with optional precision (e.g., uint[8])"""
size: Optional[Expression] = None
@dataclass
class FloatType(ClassicalType):
"""IEEE-754 floating-point type with optional size (e.g., float[64])"""
size: Optional[Expression] = None
@dataclass
class ComplexType(ClassicalType):
"""Complex type with real and imaginary parts"""
base_type: Optional[FloatType] = None
@dataclass
class AngleType(ClassicalType):
"""Angle type with optional precision"""
size: Optional[Expression] = None
@dataclass
class BitType(ClassicalType):
"""Bit type with optional size"""
size: Optional[Expression] = None
class BoolType(ClassicalType):
"""Boolean classical type"""
pass
class DurationType(ClassicalType):
"""Duration type"""
pass
class StretchType(ClassicalType):
"""Stretch type for timing"""
pass
# Array types
@dataclass
class ArrayType(ClassicalType):
"""Arrays with allocated storage"""
base_type: Union[IntType, UintType, FloatType, ComplexType, AngleType, BitType, BoolType, DurationType]
dimensions: List[Expression]
@dataclass
class ArrayReferenceType(ClassicalType):
"""Array references (typically subroutine arguments)"""
base_type: Union[IntType, UintType, FloatType, ComplexType, AngleType, BitType, BoolType, DurationType]
dimensions: Union[Expression, List[Expression]]Supporting nodes for indexing, ranges, modifiers, and other language constructs.
@dataclass
class DiscreteSet(QASMNode):
"""Set of discrete values for loops or indexing"""
values: List[Expression]
@dataclass
class RangeDefinition(QASMNode):
"""Range definition (e.g., 1:2, 1:1:10, :)"""
start: Optional[Expression] = None
end: Optional[Expression] = None
step: Optional[Expression] = None
@dataclass
class QuantumGateModifier(QASMNode):
"""Quantum gate modifier (inv, pow, ctrl, negctrl)"""
modifier: GateModifierName
argument: Optional[Expression] = None
@dataclass
class Include(Statement):
"""An include statement"""
filename: str
@dataclass
class ExpressionStatement(Statement):
"""A statement that contains a single expression"""
expression: Expression
@dataclass
class ClassicalAssignment(Statement):
"""Classical assignment statement"""
lvalue: Union[Identifier, IndexedIdentifier]
op: AssignmentOperator
rvalue: Expression
@dataclass
class AliasStatement(Statement):
"""Alias statement (e.g., let a = qubits[0];)"""
target: Identifier
value: Union[Identifier, Concatenation]Nodes for timing control and pulse-level calibration.
@dataclass
class DelayInstruction(QuantumStatement):
"""Delay instruction for timing control"""
duration: Expression
qubits: List[Union[IndexedIdentifier, Identifier]]
@dataclass
class Box(QuantumStatement):
"""Timing box for grouping quantum operations"""
duration: Optional[Expression]
body: List[QuantumStatement]
@dataclass
class CalibrationGrammarDeclaration(Statement):
"""Calibration grammar declaration"""
name: str
@dataclass
class CalibrationStatement(Statement):
"""Inline cal statement for embedded pulse-grammar interactions"""
body: str
@dataclass
class CalibrationDefinition(Statement):
"""Calibration definition for pulse-level gate definitions"""
name: Identifier
arguments: List[Union[ClassicalArgument, Expression]]
qubits: List[Identifier]
return_type: Optional[ClassicalType]
body: strfrom openqasm3 import ast
# Create a qubit declaration: qubit[2] q;
qubit_decl = ast.QubitDeclaration(
qubit=ast.Identifier("q"),
size=ast.IntegerLiteral(2)
)
# Create a gate call: h q[0];
gate_call = ast.QuantumGate(
modifiers=[],
name=ast.Identifier("h"),
arguments=[],
qubits=[ast.IndexedIdentifier(
name=ast.Identifier("q"),
indices=[[ast.IntegerLiteral(0)]]
)]
)
# Create a complete program
program = ast.Program(
version="3.0",
statements=[qubit_decl, gate_call]
)from openqasm3 import ast
# Create classical types
int_type = ast.IntType(size=ast.IntegerLiteral(32))
float_array = ast.ArrayType(
base_type=ast.FloatType(),
dimensions=[ast.IntegerLiteral(10)]
)
# Create a classical variable declaration: int[32] x = 42;
var_decl = ast.ClassicalDeclaration(
type=int_type,
identifier=ast.Identifier("x"),
init_expression=ast.IntegerLiteral(42)
)Install with Tessl CLI
npx tessl i tessl/pypi-openqasm3