OpenQasm3 package
OpenQASM 3 Python reference package
This package 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.
The AST itself is in the ast
module. There is a reference parser in the
parser
module, which requires the [parser]
extra to be installed.
With the [parser]
extra installed, the simplest interface to the parser is
the parse
function.
Abstract Syntax Tree (openqasm3.ast
)
The reference abstract syntax tree (AST) for OpenQASM 3 programs.
- class openqasm3.ast.AccessControl(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
- class openqasm3.ast.AliasStatement(target: Identifier, value: Identifier | Concatenation)
Alias statement
Example:
let a = qubits[0];
- Parameters:
target (Identifier)
value (Identifier | Concatenation)
- class openqasm3.ast.AngleType(size: Expression | None = None)
Node representing the classical
angle
type, with an optional precision.Example:
angle[8] angle[16]
- Parameters:
size (Expression | None)
- class openqasm3.ast.Annotation(keyword: str, command: str | None = None)
An annotation applied to a statement.
- class openqasm3.ast.ArrayLiteral(values: List[Expression])
Array literal, used to initialise declared arrays.
For example:
array[uint[8], 2] row = {1, 2}; array[uint[8], 2, 2] my_array = {{1, 2}, {3, 4}}; array[uint[8], 2, 2] my_array = {row, row};
- Parameters:
values (List[Expression])
- class openqasm3.ast.ArrayReferenceType(base_type: IntType | UintType | FloatType | AngleType | DurationType | BitType | BoolType | ComplexType, dimensions: Expression | List[Expression])
Type of arrays that are a reference to an array with allocated storage.
This is generally any array declared as a subroutine argument. The dimensions can be either a list of expressions (one for each dimension), or a single expression, which is the number of dimensions.
For example:
// `a` will have dimensions `[IntegerLiteral(2)]` (with a list), because // it is a 1D array, with a length of 2. def f(const array[uint[8], 2] a) {} // `b` will have dimension `IntegerLiteral(3)` (no list), because it is // a 3D array, but we don't know the lengths of its dimensions. def f(const array[uint[8], #dim=3] b) {}
- Parameters:
base_type (IntType | UintType | FloatType | AngleType | DurationType | BitType | BoolType | ComplexType)
dimensions (Expression | List[Expression])
- class openqasm3.ast.ArrayType(base_type: IntType | UintType | FloatType | AngleType | DurationType | BitType | BoolType | ComplexType, dimensions: List[Expression])
Type of arrays that include allocation of the storage.
This is generally any array declared as a standard statement, but not arrays declared by being arguments to subroutines.
- Parameters:
base_type (IntType | UintType | FloatType | AngleType | DurationType | BitType | BoolType | ComplexType)
dimensions (List[Expression])
- class openqasm3.ast.AssignmentOperator(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
- class openqasm3.ast.BinaryExpression(op: BinaryOperator, lhs: Expression, rhs: Expression)
A binary expression
Example:
q1 || q2
- Parameters:
op (BinaryOperator)
lhs (Expression)
rhs (Expression)
- class openqasm3.ast.BinaryOperator(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
- class openqasm3.ast.BitType(size: Expression | None = None)
Node representing the classical
bit
type, with an optional size.Example:
bit[8] creg[8]
- Parameters:
size (Expression | None)
- class openqasm3.ast.BitstringLiteral(value: int, width: int)
A literal bitstring value. The
value
is the numerical value of the bitstring, and thewidth
is the number of digits given.
- class openqasm3.ast.BoolType
Leaf node representing the Boolean classical type.
- class openqasm3.ast.BooleanLiteral(value: bool)
A boolean expression
Example:
true false
- Parameters:
value (bool)
- class openqasm3.ast.Box(duration: Expression | None, body: List[QuantumStatement])
Timing box
Example:
box [maxdur] { delay[start_stretch] $0; x $0; }
- Parameters:
duration (Expression | None)
body (List[QuantumStatement])
- class openqasm3.ast.BranchingStatement(condition: Expression, if_block: List[Statement], else_block: List[Statement])
Branch (
if
) statementExample:
if (temp == 1) { ry(-pi / 2) scratch[0]; } else continue;
- Parameters:
condition (Expression)
- class openqasm3.ast.BreakStatement
Break statement
Example:
break;
- class openqasm3.ast.CalibrationDefinition(name: Identifier, arguments: List[ClassicalArgument | Expression], qubits: List[Identifier], return_type: ClassicalType | None, body: str)
Calibration definition
Example:
defcal rz(angle[20] theta) q { shift_phase drive(q), -theta; }
- Parameters:
name (Identifier)
arguments (List[ClassicalArgument | Expression])
qubits (List[Identifier])
return_type (ClassicalType | None)
body (str)
- class openqasm3.ast.CalibrationGrammarDeclaration(name: str)
Calibration grammar declaration
Example:
defcalgrammar "openpulse";
- Parameters:
name (str)
- class openqasm3.ast.CalibrationStatement(body: str)
An inline
cal
statement for embedded pulse-grammar interactions.Example:
cal { shift_phase(drive($0), theta); }
- Parameters:
body (str)
- class openqasm3.ast.Cast(type: ClassicalType, argument: Expression)
A cast call expression
Example:
counts += int[1](b);
- Parameters:
type (ClassicalType)
argument (Expression)
- class openqasm3.ast.ClassicalArgument(type: ClassicalType, name: Identifier, access: AccessControl | None = None)
Classical argument for a gate or subroutine declaration
- Parameters:
type (ClassicalType)
name (Identifier)
access (AccessControl | None)
- class openqasm3.ast.ClassicalAssignment(lvalue: Identifier | IndexedIdentifier, op: AssignmentOperator, rvalue: Expression)
Classical assignment
Example:
a[0] = 1;
- Parameters:
lvalue (Identifier | IndexedIdentifier)
op (AssignmentOperator)
rvalue (Expression)
- class openqasm3.ast.ClassicalDeclaration(type: ClassicalType, identifier: Identifier, init_expression: Expression | QuantumMeasurement | None = None)
Classical variable declaration
Example:
bit c;
- Parameters:
type (ClassicalType)
identifier (Identifier)
init_expression (Expression | QuantumMeasurement | None)
- class openqasm3.ast.ClassicalType
Base class for classical type
- class openqasm3.ast.ComplexType(base_type: FloatType | None)
Complex ClassicalType. Its real and imaginary parts are based on other classical types.
Example:
complex[float] complex[float[32]]
- Parameters:
base_type (FloatType | None)
- class openqasm3.ast.CompoundStatement(statements: List[Statement])
A sequence of statements enclosed within an anonymous scope block
- class openqasm3.ast.Concatenation(lhs: Expression, rhs: Expression)
Concatenation of two registers, for example:
a ++ b a[2:3] ++ a[0:1]
- Parameters:
lhs (Expression)
rhs (Expression)
- class openqasm3.ast.ConstantDeclaration(type: ClassicalType, identifier: Identifier, init_expression: Expression)
Constant declaration
Example:
const int[16] n = 10;
- Parameters:
type (ClassicalType)
identifier (Identifier)
init_expression (Expression)
- class openqasm3.ast.ContinueStatement
Continue statement
Example:
continue;
- class openqasm3.ast.DelayInstruction(duration: Expression, qubits: List[IndexedIdentifier | Identifier])
Delay instruction
Example:
delay[start_stretch] $0;
- Parameters:
duration (Expression)
qubits (List[IndexedIdentifier | Identifier])
- class openqasm3.ast.DiscreteSet(values: List[Expression])
A set of discrete values. This can be used for the values in a
for
loop, or to index certain values out of a register:for i in {1, 2, 3} {} let alias = qubits[{2, 3, 4}];
- Parameters:
values (List[Expression])
- class openqasm3.ast.DurationLiteral(value: float, unit: TimeUnit)
A duration literal
Example:
1.0ns
- class openqasm3.ast.DurationType
Leaf node representing the
duration
type.
- class openqasm3.ast.EndStatement
End statement
Example:
end;
- class openqasm3.ast.Expression
An expression: anything that returns a value
- class openqasm3.ast.ExpressionStatement(expression: Expression)
A statement that contains a single expression
- Parameters:
expression (Expression)
- class openqasm3.ast.ExternArgument(type: ClassicalType, access: AccessControl | None = None)
Classical argument for an extern declaration.
- Parameters:
type (ClassicalType)
access (AccessControl | None)
- class openqasm3.ast.ExternDeclaration(name: Identifier, arguments: List[ExternArgument], return_type: ClassicalType | None = None)
A extern declaration
Example:
extern get_pauli(int[prec]) -> bit[2 * n]; get_pauli // <- name int[prec] // <- classical type bit[2 * n] // <- return type
- Parameters:
name (Identifier)
arguments (List[ExternArgument])
return_type (ClassicalType | None)
- class openqasm3.ast.FloatLiteral(value: float)
An real number literal
Example:
1.1
- Parameters:
value (float)
- class openqasm3.ast.FloatType(size: Expression | None = None)
Node representing the classical
float
type, with the particular IEEE-754 floating-point size optionally specified.Example:
float[16] float[64]
- Parameters:
size (Expression | None)
- class openqasm3.ast.ForInLoop(type: ClassicalType, identifier: Identifier, set_declaration: RangeDefinition | DiscreteSet | Expression, block: List[Statement])
For in loop
Example:
for i in [0: 2] { majority a[i], b[i + 1], a[i + 1]; }
- Parameters:
type (ClassicalType)
identifier (Identifier)
set_declaration (RangeDefinition | DiscreteSet | Expression)
- class openqasm3.ast.FunctionCall(name: Identifier, arguments: List[Expression])
A function call expression
Example:
foo(1) foo // <- name
- Parameters:
name (Identifier)
arguments (List[Expression])
- openqasm3.ast.GateModifierName
alias of
GateModifier
- class openqasm3.ast.IODeclaration(io_identifier: IOKeyword, type: ClassicalType, identifier: Identifier)
Input/output variable declaration
Exampe:
input angle[16] theta; output bit select;
- Parameters:
io_identifier (IOKeyword)
type (ClassicalType)
identifier (Identifier)
- class openqasm3.ast.IOKeyword(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
- class openqasm3.ast.ImaginaryLiteral(value: float)
An real number literal
Example:
1.1im
- Parameters:
value (float)
- class openqasm3.ast.IndexExpression(collection: Expression, index: DiscreteSet | List[Expression | RangeDefinition])
An index expression.
Example:
q[1]
- Parameters:
collection (Expression)
index (DiscreteSet | List[Expression | RangeDefinition])
- class openqasm3.ast.IndexedIdentifier(name: Identifier, indices: List[DiscreteSet | List[Expression | RangeDefinition]])
An indentifier with index operators, such that it can be used as an lvalue. The list of indices is subsequent index brackets, so in:
a[{1, 2, 3}][0:1, 0:1]
the list of indices will have two elements. The first will be a
DiscreteSet
, and the second will be a list of twoRangeDefinition
s.- Parameters:
name (Identifier)
indices (List[DiscreteSet | List[Expression | RangeDefinition]])
- class openqasm3.ast.IntType(size: Expression | None = None)
Node representing a classical
int
(signed integer) type, with an optional precision.Example:
int[8] int[16]
- Parameters:
size (Expression | None)
- class openqasm3.ast.IntegerLiteral(value: int)
An integer literal
Example:
1
- Parameters:
value (int)
- class openqasm3.ast.Program(statements: List[Statement | Pragma], version: str | None = None)
An entire OpenQASM 3 program represented by a list of top level statements
- class openqasm3.ast.QASMNode
Base class for all OpenQASM 3 nodes
- class openqasm3.ast.QuantumArgument(name: Identifier, size: Expression | None = None)
Quantum argument for a subroutine declaration
- Parameters:
name (Identifier)
size (Expression | None)
- class openqasm3.ast.QuantumBarrier(qubits: List[Expression])
A quantum barrier instruction
Example:
barrier q;
- Parameters:
qubits (List[Expression])
- class openqasm3.ast.QuantumGate(modifiers: List[QuantumGateModifier], name: Identifier, arguments: List[Expression], qubits: List[IndexedIdentifier | Identifier], duration: Expression | None = None)
Invoking a quantum gate
- Example::
cx[dur] 0, 1;
or
ctrl @ p(λ) a, b;
ctrl @ // <- quantumGateModifier p // <- quantumGateName λ // <- argument a, b // <- qubit
- Parameters:
modifiers (List[QuantumGateModifier])
name (Identifier)
arguments (List[Expression])
qubits (List[IndexedIdentifier | Identifier])
duration (Expression | None)
- class openqasm3.ast.QuantumGateDefinition(name: Identifier, arguments: List[Identifier], qubits: List[Identifier], body: List[QuantumStatement])
Define a new quantum gate
Example:
gate cx c, t { ctrl @ unitary(pi, 0, pi) c, t; }
- Parameters:
name (Identifier)
arguments (List[Identifier])
qubits (List[Identifier])
body (List[QuantumStatement])
- class openqasm3.ast.QuantumGateModifier(modifier: GateModifier, argument: Expression | None = None)
A quantum gate modifier
- Attributes:
modifier: ‘inv’, ‘pow’, or ‘ctrl’ expression: only pow modifier has expression.
Example:
inv @ pow(1./2.) ctrl
- Parameters:
modifier (GateModifier)
argument (Expression | None)
- class openqasm3.ast.QuantumMeasurement(qubit: IndexedIdentifier | Identifier)
A quantum measurement instruction
Example:
measure q;
- Parameters:
qubit (IndexedIdentifier | Identifier)
- class openqasm3.ast.QuantumMeasurementStatement(measure: QuantumMeasurement, target: IndexedIdentifier | Identifier | None)
Stand-alone statement of a quantum measurement, potentially assigning the result to a classical variable. This is not the only statement that measure can appear in (it can also be in classical declaration statements and returns).
- Parameters:
measure (QuantumMeasurement)
target (IndexedIdentifier | Identifier | None)
- class openqasm3.ast.QuantumPhase(modifiers: List[QuantumGateModifier], argument: Expression, qubits: List[IndexedIdentifier | Identifier])
A quantum phase instruction
Example:
ctrl @ gphase(λ) a; ctrl @ // <- quantumGateModifier λ // <- argument a // <- qubit
- Parameters:
modifiers (List[QuantumGateModifier])
argument (Expression)
qubits (List[IndexedIdentifier | Identifier])
- class openqasm3.ast.QuantumReset(qubits: IndexedIdentifier | Identifier)
A reset instruction.
Example:
reset q;
- Parameters:
qubits (IndexedIdentifier | Identifier)
- class openqasm3.ast.QuantumStatement
Statements that may appear inside a gate declaration
- class openqasm3.ast.QubitDeclaration(qubit: Identifier, size: Expression | None = None)
Global qubit declaration
Example:
qubit q; qubit[4] q; q // <- qubit 4 // <- size
- Parameters:
qubit (Identifier)
size (Expression | None)
- class openqasm3.ast.RangeDefinition(start: Expression | None, end: Expression | None, step: Expression | None)
Range definition.
Example:
1:2 1:1:10 :
- Parameters:
start (Expression | None)
end (Expression | None)
step (Expression | None)
- class openqasm3.ast.ReturnStatement(expression: Expression | QuantumMeasurement | None = None)
Classical or quantum return statement
Example:
return measure q; return a + b
- Parameters:
expression (Expression | QuantumMeasurement | None)
- class openqasm3.ast.SizeOf(target: Expression, index: Expression | None = None)
sizeof
an array’s dimensions.- Parameters:
target (Expression)
index (Expression | None)
- class openqasm3.ast.Span(start_line: int, start_column: int, end_line: int, end_column: int)
Start and end line/column in the source file We use the Antlr convention. The starting line number is 1 and starting column number is 0.
- class openqasm3.ast.Statement
A statement: anything that can appear on its own line
- class openqasm3.ast.StretchType
Leaf node representing the
stretch
type.
- class openqasm3.ast.SubroutineDefinition(name: Identifier, arguments: List[ClassicalArgument | QuantumArgument], body: List[Statement], return_type: ClassicalType | None = None)
Subroutine definition
Example:
def measure(qubit q) -> bit { s q; h q; return measure q; }
- Parameters:
name (Identifier)
arguments (List[ClassicalArgument | QuantumArgument])
return_type (ClassicalType | None)
- class openqasm3.ast.SwitchStatement(target: Expression, cases: List[Tuple[List[Expression], CompoundStatement]], default: CompoundStatement | None)
A switch-case statement.
The literal cases are stored in the cases dictionary, in declaration order. Python’s dict guarantees (for all supported versions of Python) that the iteration order will be insertion order, so this field is ordered.
The default case, if any, is in the default attribute.
- Parameters:
target (Expression)
cases (List[Tuple[List[Expression], CompoundStatement]])
default (CompoundStatement | None)
- class openqasm3.ast.TimeUnit(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
- class openqasm3.ast.UintType(size: Expression | None = None)
Node representing a classical
uint
(unsigned integer) type, with an optional precision.Example:
uint[8] uint[16]
- Parameters:
size (Expression | None)
- class openqasm3.ast.UnaryExpression(op: UnaryOperator, expression: Expression)
A unary expression
Example:
~b !bool -i
- Parameters:
op (UnaryOperator)
expression (Expression)
- class openqasm3.ast.UnaryOperator(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
- class openqasm3.ast.WhileLoop(while_condition: Expression, block: List[Statement])
While loop
Example:
while(~success) { reset magic; ry(pi / 4) magic; success = distill(magic, scratch); }
- Parameters:
while_condition (Expression)
AST Visitors and Transformers (openqasm3.visitor
)
Implementation of an example AST visitor QASMVisitor
, which can be
inherited from to make generic visitors of the reference AST. Deriving from
this is QASMTransformer
, which is an example of how the AST can be
manipulated.
- class openqasm3.visitor.QASMTransformer
A
QASMVisitor
subclass that walks the abstract syntax tree and allows modification of nodes.Modified from the implementation in ast.py in the Python standard library
- class openqasm3.visitor.QASMVisitor
A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the visit method.
Modified from the implementation in ast.py in the Python standard library. We added the context argument to the visit method. It allows the visitor to hold temporary state while visiting the nodes.
The optional context argument in visit/generic_visit methods can be used to hold temporary information that we do not want to hold in either the AST or the visitor themselves.