lca_index
int64 0
223
| idx
stringlengths 7
11
| line_type
stringclasses 6
values | ground_truth
stringlengths 2
35
| completions
sequencelengths 3
1.16k
| prefix
stringlengths 298
32.8k
| postfix
stringlengths 0
28.6k
| repo
stringclasses 34
values |
---|---|---|---|---|---|---|---|
87 | 87-578-53 | infile | name | [
"name",
"span",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node. | }"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-581-24 | inproject | CalibrationDefinition | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast. | , context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-600-24 | inproject | SubroutineDefinition | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast. | , context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-636-13 | infile | _write_statement | [
"chain_else_if",
"generic_visit",
"indent",
"old_measurement",
"stream",
"visit",
"visit_AliasStatement",
"visit_AngleType",
"visit_ArrayLiteral",
"visit_ArrayReferenceType",
"visit_ArrayType",
"visit_BinaryExpression",
"visit_BitstringLiteral",
"visit_BitType",
"visit_BooleanLiteral",
"visit_BoolType",
"visit_Box",
"visit_BranchingStatement",
"visit_BreakStatement",
"visit_CalibrationDefinition",
"visit_CalibrationGrammarDeclaration",
"visit_Cast",
"visit_ClassicalArgument",
"visit_ClassicalAssignment",
"visit_ClassicalDeclaration",
"visit_ComplexType",
"visit_Concatenation",
"visit_ConstantDeclaration",
"visit_ContinueStatement",
"visit_DelayInstruction",
"visit_DiscreteSet",
"visit_DurationLiteral",
"visit_DurationOf",
"visit_DurationType",
"visit_EndStatement",
"visit_ExpressionStatement",
"visit_ExternArgument",
"visit_ExternDeclaration",
"visit_FloatLiteral",
"visit_FloatType",
"visit_ForInLoop",
"visit_FunctionCall",
"visit_Identifier",
"visit_Include",
"visit_IndexedIdentifier",
"visit_IndexExpression",
"visit_IntegerLiteral",
"visit_IntType",
"visit_IODeclaration",
"visit_Pragma",
"visit_Program",
"visit_QuantumArgument",
"visit_QuantumBarrier",
"visit_QuantumGate",
"visit_QuantumGateDefinition",
"visit_QuantumGateModifier",
"visit_QuantumMeasurement",
"visit_QuantumMeasurementStatement",
"visit_QuantumPhase",
"visit_QuantumReset",
"visit_QubitDeclaration",
"visit_RangeDefinition",
"visit_ReturnStatement",
"visit_SizeOf",
"visit_StretchType",
"visit_SubroutineDefinition",
"visit_UintType",
"visit_UnaryExpression",
"visit_WhileLoop",
"_end_line",
"_end_statement",
"_start_line",
"_visit_sequence",
"_write_statement",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self. | ("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-639-13 | infile | _write_statement | [
"chain_else_if",
"generic_visit",
"indent",
"old_measurement",
"stream",
"visit",
"visit_AliasStatement",
"visit_AngleType",
"visit_ArrayLiteral",
"visit_ArrayReferenceType",
"visit_ArrayType",
"visit_BinaryExpression",
"visit_BitstringLiteral",
"visit_BitType",
"visit_BooleanLiteral",
"visit_BoolType",
"visit_Box",
"visit_BranchingStatement",
"visit_BreakStatement",
"visit_CalibrationDefinition",
"visit_CalibrationGrammarDeclaration",
"visit_Cast",
"visit_ClassicalArgument",
"visit_ClassicalAssignment",
"visit_ClassicalDeclaration",
"visit_ComplexType",
"visit_Concatenation",
"visit_ConstantDeclaration",
"visit_ContinueStatement",
"visit_DelayInstruction",
"visit_DiscreteSet",
"visit_DurationLiteral",
"visit_DurationOf",
"visit_DurationType",
"visit_EndStatement",
"visit_ExpressionStatement",
"visit_ExternArgument",
"visit_ExternDeclaration",
"visit_FloatLiteral",
"visit_FloatType",
"visit_ForInLoop",
"visit_FunctionCall",
"visit_Identifier",
"visit_Include",
"visit_IndexedIdentifier",
"visit_IndexExpression",
"visit_IntegerLiteral",
"visit_IntType",
"visit_IODeclaration",
"visit_Pragma",
"visit_Program",
"visit_QuantumArgument",
"visit_QuantumBarrier",
"visit_QuantumGate",
"visit_QuantumGateDefinition",
"visit_QuantumGateModifier",
"visit_QuantumMeasurement",
"visit_QuantumMeasurementStatement",
"visit_QuantumPhase",
"visit_QuantumReset",
"visit_QubitDeclaration",
"visit_RangeDefinition",
"visit_ReturnStatement",
"visit_SizeOf",
"visit_StretchType",
"visit_SubroutineDefinition",
"visit_UintType",
"visit_UnaryExpression",
"visit_WhileLoop",
"_end_line",
"_end_statement",
"_start_line",
"_visit_sequence",
"_write_statement",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self. | ("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-642-13 | infile | _write_statement | [
"chain_else_if",
"generic_visit",
"indent",
"old_measurement",
"stream",
"visit",
"visit_AliasStatement",
"visit_AngleType",
"visit_ArrayLiteral",
"visit_ArrayReferenceType",
"visit_ArrayType",
"visit_BinaryExpression",
"visit_BitstringLiteral",
"visit_BitType",
"visit_BooleanLiteral",
"visit_BoolType",
"visit_Box",
"visit_BranchingStatement",
"visit_BreakStatement",
"visit_CalibrationDefinition",
"visit_CalibrationGrammarDeclaration",
"visit_Cast",
"visit_ClassicalArgument",
"visit_ClassicalAssignment",
"visit_ClassicalDeclaration",
"visit_ComplexType",
"visit_Concatenation",
"visit_ConstantDeclaration",
"visit_ContinueStatement",
"visit_DelayInstruction",
"visit_DiscreteSet",
"visit_DurationLiteral",
"visit_DurationOf",
"visit_DurationType",
"visit_EndStatement",
"visit_ExpressionStatement",
"visit_ExternArgument",
"visit_ExternDeclaration",
"visit_FloatLiteral",
"visit_FloatType",
"visit_ForInLoop",
"visit_FunctionCall",
"visit_Identifier",
"visit_Include",
"visit_IndexedIdentifier",
"visit_IndexExpression",
"visit_IntegerLiteral",
"visit_IntType",
"visit_IODeclaration",
"visit_Pragma",
"visit_Program",
"visit_QuantumArgument",
"visit_QuantumBarrier",
"visit_QuantumGate",
"visit_QuantumGateDefinition",
"visit_QuantumGateModifier",
"visit_QuantumMeasurement",
"visit_QuantumMeasurementStatement",
"visit_QuantumPhase",
"visit_QuantumReset",
"visit_QubitDeclaration",
"visit_RangeDefinition",
"visit_ReturnStatement",
"visit_SizeOf",
"visit_StretchType",
"visit_SubroutineDefinition",
"visit_UintType",
"visit_UnaryExpression",
"visit_WhileLoop",
"_end_line",
"_end_statement",
"_start_line",
"_visit_sequence",
"_write_statement",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self. | ("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-665-36 | inproject | else_block | [
"condition",
"else_block",
"if_block",
"span",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node. | [0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-665-55 | inproject | BranchingStatement | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast. | )
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-687-13 | infile | _end_line | [
"chain_else_if",
"generic_visit",
"indent",
"old_measurement",
"stream",
"visit",
"visit_AliasStatement",
"visit_AngleType",
"visit_ArrayLiteral",
"visit_ArrayReferenceType",
"visit_ArrayType",
"visit_BinaryExpression",
"visit_BitstringLiteral",
"visit_BitType",
"visit_BooleanLiteral",
"visit_BoolType",
"visit_Box",
"visit_BranchingStatement",
"visit_BreakStatement",
"visit_CalibrationDefinition",
"visit_CalibrationGrammarDeclaration",
"visit_Cast",
"visit_ClassicalArgument",
"visit_ClassicalAssignment",
"visit_ClassicalDeclaration",
"visit_ComplexType",
"visit_Concatenation",
"visit_ConstantDeclaration",
"visit_ContinueStatement",
"visit_DelayInstruction",
"visit_DiscreteSet",
"visit_DurationLiteral",
"visit_DurationOf",
"visit_DurationType",
"visit_EndStatement",
"visit_ExpressionStatement",
"visit_ExternArgument",
"visit_ExternDeclaration",
"visit_FloatLiteral",
"visit_FloatType",
"visit_ForInLoop",
"visit_FunctionCall",
"visit_Identifier",
"visit_Include",
"visit_IndexedIdentifier",
"visit_IndexExpression",
"visit_IntegerLiteral",
"visit_IntType",
"visit_IODeclaration",
"visit_Pragma",
"visit_Program",
"visit_QuantumArgument",
"visit_QuantumBarrier",
"visit_QuantumGate",
"visit_QuantumGateDefinition",
"visit_QuantumGateModifier",
"visit_QuantumMeasurement",
"visit_QuantumMeasurementStatement",
"visit_QuantumPhase",
"visit_QuantumReset",
"visit_QubitDeclaration",
"visit_RangeDefinition",
"visit_ReturnStatement",
"visit_SizeOf",
"visit_StretchType",
"visit_SubroutineDefinition",
"visit_UintType",
"visit_UnaryExpression",
"visit_WhileLoop",
"_end_line",
"_end_statement",
"_start_line",
"_visit_sequence",
"_write_statement",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self. | (context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-698-13 | infile | visit | [
"chain_else_if",
"generic_visit",
"indent",
"old_measurement",
"stream",
"visit",
"visit_AliasStatement",
"visit_AngleType",
"visit_ArrayLiteral",
"visit_ArrayReferenceType",
"visit_ArrayType",
"visit_BinaryExpression",
"visit_BitstringLiteral",
"visit_BitType",
"visit_BooleanLiteral",
"visit_BoolType",
"visit_Box",
"visit_BranchingStatement",
"visit_BreakStatement",
"visit_CalibrationDefinition",
"visit_CalibrationGrammarDeclaration",
"visit_Cast",
"visit_ClassicalArgument",
"visit_ClassicalAssignment",
"visit_ClassicalDeclaration",
"visit_ComplexType",
"visit_Concatenation",
"visit_ConstantDeclaration",
"visit_ContinueStatement",
"visit_DelayInstruction",
"visit_DiscreteSet",
"visit_DurationLiteral",
"visit_DurationOf",
"visit_DurationType",
"visit_EndStatement",
"visit_ExpressionStatement",
"visit_ExternArgument",
"visit_ExternDeclaration",
"visit_FloatLiteral",
"visit_FloatType",
"visit_ForInLoop",
"visit_FunctionCall",
"visit_Identifier",
"visit_Include",
"visit_IndexedIdentifier",
"visit_IndexExpression",
"visit_IntegerLiteral",
"visit_IntType",
"visit_IODeclaration",
"visit_Pragma",
"visit_Program",
"visit_QuantumArgument",
"visit_QuantumBarrier",
"visit_QuantumGate",
"visit_QuantumGateDefinition",
"visit_QuantumGateModifier",
"visit_QuantumMeasurement",
"visit_QuantumMeasurementStatement",
"visit_QuantumPhase",
"visit_QuantumReset",
"visit_QubitDeclaration",
"visit_RangeDefinition",
"visit_ReturnStatement",
"visit_SizeOf",
"visit_StretchType",
"visit_SubroutineDefinition",
"visit_UintType",
"visit_UnaryExpression",
"visit_WhileLoop",
"_end_line",
"_end_statement",
"_start_line",
"_visit_sequence",
"_write_statement",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self. | (node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-698-24 | infile | loop_variable | [
"block",
"loop_variable",
"set_declaration",
"span",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node. | , context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-700-27 | inproject | set_declaration | [
"block",
"loop_variable",
"set_declaration",
"span",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node. | , ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-700-48 | inproject | RangeDefinition | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast. | ):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-705-17 | infile | visit | [
"chain_else_if",
"generic_visit",
"indent",
"old_measurement",
"stream",
"visit",
"visit_AliasStatement",
"visit_AngleType",
"visit_ArrayLiteral",
"visit_ArrayReferenceType",
"visit_ArrayType",
"visit_BinaryExpression",
"visit_BitstringLiteral",
"visit_BitType",
"visit_BooleanLiteral",
"visit_BoolType",
"visit_Box",
"visit_BranchingStatement",
"visit_BreakStatement",
"visit_CalibrationDefinition",
"visit_CalibrationGrammarDeclaration",
"visit_Cast",
"visit_ClassicalArgument",
"visit_ClassicalAssignment",
"visit_ClassicalDeclaration",
"visit_ComplexType",
"visit_Concatenation",
"visit_ConstantDeclaration",
"visit_ContinueStatement",
"visit_DelayInstruction",
"visit_DiscreteSet",
"visit_DurationLiteral",
"visit_DurationOf",
"visit_DurationType",
"visit_EndStatement",
"visit_ExpressionStatement",
"visit_ExternArgument",
"visit_ExternDeclaration",
"visit_FloatLiteral",
"visit_FloatType",
"visit_ForInLoop",
"visit_FunctionCall",
"visit_Identifier",
"visit_Include",
"visit_IndexedIdentifier",
"visit_IndexExpression",
"visit_IntegerLiteral",
"visit_IntType",
"visit_IODeclaration",
"visit_Pragma",
"visit_Program",
"visit_QuantumArgument",
"visit_QuantumBarrier",
"visit_QuantumGate",
"visit_QuantumGateDefinition",
"visit_QuantumGateModifier",
"visit_QuantumMeasurement",
"visit_QuantumMeasurementStatement",
"visit_QuantumPhase",
"visit_QuantumReset",
"visit_QubitDeclaration",
"visit_RangeDefinition",
"visit_ReturnStatement",
"visit_SizeOf",
"visit_StretchType",
"visit_SubroutineDefinition",
"visit_UintType",
"visit_UnaryExpression",
"visit_WhileLoop",
"_end_line",
"_end_statement",
"_start_line",
"_visit_sequence",
"_write_statement",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self. | (node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-705-28 | infile | set_declaration | [
"block",
"loop_variable",
"set_declaration",
"span",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node. | , context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-741-27 | inproject | target | [
"span",
"target",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node. | , ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-741-39 | inproject | QASMNode | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast. | ):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-756-16 | common | index | [
"index",
"span",
"target",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node. | is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-758-17 | infile | visit | [
"chain_else_if",
"generic_visit",
"indent",
"old_measurement",
"stream",
"visit",
"visit_AliasStatement",
"visit_AngleType",
"visit_ArrayLiteral",
"visit_ArrayReferenceType",
"visit_ArrayType",
"visit_BinaryExpression",
"visit_BitstringLiteral",
"visit_BitType",
"visit_BooleanLiteral",
"visit_BoolType",
"visit_Box",
"visit_BranchingStatement",
"visit_BreakStatement",
"visit_CalibrationDefinition",
"visit_CalibrationGrammarDeclaration",
"visit_Cast",
"visit_ClassicalArgument",
"visit_ClassicalAssignment",
"visit_ClassicalDeclaration",
"visit_ComplexType",
"visit_Concatenation",
"visit_ConstantDeclaration",
"visit_ContinueStatement",
"visit_DelayInstruction",
"visit_DiscreteSet",
"visit_DurationLiteral",
"visit_DurationOf",
"visit_DurationType",
"visit_EndStatement",
"visit_ExpressionStatement",
"visit_ExternArgument",
"visit_ExternDeclaration",
"visit_FloatLiteral",
"visit_FloatType",
"visit_ForInLoop",
"visit_FunctionCall",
"visit_Identifier",
"visit_Include",
"visit_IndexedIdentifier",
"visit_IndexExpression",
"visit_IntegerLiteral",
"visit_IntType",
"visit_IODeclaration",
"visit_Pragma",
"visit_Program",
"visit_QuantumArgument",
"visit_QuantumBarrier",
"visit_QuantumGate",
"visit_QuantumGateDefinition",
"visit_QuantumGateModifier",
"visit_QuantumMeasurement",
"visit_QuantumMeasurementStatement",
"visit_QuantumPhase",
"visit_QuantumReset",
"visit_QubitDeclaration",
"visit_RangeDefinition",
"visit_ReturnStatement",
"visit_SizeOf",
"visit_StretchType",
"visit_SubroutineDefinition",
"visit_UintType",
"visit_UnaryExpression",
"visit_WhileLoop",
"_end_line",
"_end_statement",
"_start_line",
"_visit_sequence",
"_write_statement",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self. | (node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-758-28 | infile | index | [
"index",
"span",
"target",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node. | )
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-766-13 | infile | visit | [
"chain_else_if",
"generic_visit",
"indent",
"old_measurement",
"stream",
"visit",
"visit_AliasStatement",
"visit_AngleType",
"visit_ArrayLiteral",
"visit_ArrayReferenceType",
"visit_ArrayType",
"visit_BinaryExpression",
"visit_BitstringLiteral",
"visit_BitType",
"visit_BooleanLiteral",
"visit_BoolType",
"visit_Box",
"visit_BranchingStatement",
"visit_BreakStatement",
"visit_CalibrationDefinition",
"visit_CalibrationGrammarDeclaration",
"visit_Cast",
"visit_ClassicalArgument",
"visit_ClassicalAssignment",
"visit_ClassicalDeclaration",
"visit_ComplexType",
"visit_Concatenation",
"visit_ConstantDeclaration",
"visit_ContinueStatement",
"visit_DelayInstruction",
"visit_DiscreteSet",
"visit_DurationLiteral",
"visit_DurationOf",
"visit_DurationType",
"visit_EndStatement",
"visit_ExpressionStatement",
"visit_ExternArgument",
"visit_ExternDeclaration",
"visit_FloatLiteral",
"visit_FloatType",
"visit_ForInLoop",
"visit_FunctionCall",
"visit_Identifier",
"visit_Include",
"visit_IndexedIdentifier",
"visit_IndexExpression",
"visit_IntegerLiteral",
"visit_IntType",
"visit_IODeclaration",
"visit_Pragma",
"visit_Program",
"visit_QuantumArgument",
"visit_QuantumBarrier",
"visit_QuantumGate",
"visit_QuantumGateDefinition",
"visit_QuantumGateModifier",
"visit_QuantumMeasurement",
"visit_QuantumMeasurementStatement",
"visit_QuantumPhase",
"visit_QuantumReset",
"visit_QubitDeclaration",
"visit_RangeDefinition",
"visit_ReturnStatement",
"visit_SizeOf",
"visit_StretchType",
"visit_SubroutineDefinition",
"visit_UintType",
"visit_UnaryExpression",
"visit_WhileLoop",
"_end_line",
"_end_statement",
"_start_line",
"_visit_sequence",
"_write_statement",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self. | (node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-766-24 | infile | value | [
"span",
"target",
"value",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node. | , context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-770-24 | inproject | ClassicalAssignment | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast. | , context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-775-13 | infile | visit | [
"chain_else_if",
"generic_visit",
"indent",
"old_measurement",
"stream",
"visit",
"visit_AliasStatement",
"visit_AngleType",
"visit_ArrayLiteral",
"visit_ArrayReferenceType",
"visit_ArrayType",
"visit_BinaryExpression",
"visit_BitstringLiteral",
"visit_BitType",
"visit_BooleanLiteral",
"visit_BoolType",
"visit_Box",
"visit_BranchingStatement",
"visit_BreakStatement",
"visit_CalibrationDefinition",
"visit_CalibrationGrammarDeclaration",
"visit_Cast",
"visit_ClassicalArgument",
"visit_ClassicalAssignment",
"visit_ClassicalDeclaration",
"visit_ComplexType",
"visit_Concatenation",
"visit_ConstantDeclaration",
"visit_ContinueStatement",
"visit_DelayInstruction",
"visit_DiscreteSet",
"visit_DurationLiteral",
"visit_DurationOf",
"visit_DurationType",
"visit_EndStatement",
"visit_ExpressionStatement",
"visit_ExternArgument",
"visit_ExternDeclaration",
"visit_FloatLiteral",
"visit_FloatType",
"visit_ForInLoop",
"visit_FunctionCall",
"visit_Identifier",
"visit_Include",
"visit_IndexedIdentifier",
"visit_IndexExpression",
"visit_IntegerLiteral",
"visit_IntType",
"visit_IODeclaration",
"visit_Pragma",
"visit_Program",
"visit_QuantumArgument",
"visit_QuantumBarrier",
"visit_QuantumGate",
"visit_QuantumGateDefinition",
"visit_QuantumGateModifier",
"visit_QuantumMeasurement",
"visit_QuantumMeasurementStatement",
"visit_QuantumPhase",
"visit_QuantumReset",
"visit_QubitDeclaration",
"visit_RangeDefinition",
"visit_ReturnStatement",
"visit_SizeOf",
"visit_StretchType",
"visit_SubroutineDefinition",
"visit_UintType",
"visit_UnaryExpression",
"visit_WhileLoop",
"_end_line",
"_end_statement",
"_start_line",
"_visit_sequence",
"_write_statement",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self. | (node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-775-24 | infile | rvalue | [
"lvalue",
"op",
"rvalue",
"span",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node. | , context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context.increase_scope():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
87 | 87-782-21 | infile | increase_scope | [
"current_indent",
"increase_scope",
"skip_next_indent",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
==============================================================
Generating OpenQASM 3 from an AST Node (``openqasm3.printer``)
==============================================================
.. currentmodule:: openqasm3
It is often useful to go from the :mod:`AST representation <openqasm3.ast>` of an OpenQASM 3 program
back to the textual language. The functions and classes described here will do this conversion.
Most uses should be covered by using :func:`dump` to write to an open text stream (an open file, for
example) or :func:`dumps` to produce a string. Both of these accept :ref:`several keyword arguments
<printer-kwargs>` that control the formatting of the output.
.. autofunction:: openqasm3.dump
.. autofunction:: openqasm3.dumps
.. _printer-kwargs:
Controlling the formatting
==========================
.. currentmodule:: openqasm3.printer
The :func:`~openqasm3.dump` and :func:`~openqasm3.dumps` functions both use an internal AST-visitor
class to operate on the AST. This class actually defines all the formatting options, and can be
used for more low-level operations, such as writing a program piece-by-piece. This may need access
to the :ref:`printer state <printer-state>`, documented below.
.. autoclass:: Printer
:members:
:class-doc-from: both
For the most complete control, it is possible to subclass this printer and override only the visitor
methods that should be modified.
.. _printer-state:
Reusing the same printer
========================
.. currentmodule:: openqasm3.printer
If the :class:`Printer` is being reused to write multiple nodes to a single stream, you will also
likely need to access its internal state. This can be done by manually creating a
:class:`PrinterState` object and passing it in the original call to :meth:`Printer.visit`. The
state object is mutated by the visit, and will reflect the output state at the end.
.. autoclass:: PrinterState
:members:
"""
import contextlib
import dataclasses
import io
from typing import Sequence, Optional
from . import ast, properties
from .visitor import QASMVisitor
__all__ = ("dump", "dumps", "Printer", "PrinterState")
def dump(node: ast.QASMNode, file: io.TextIOBase, **kwargs) -> None:
"""Write textual OpenQASM 3 code representing ``node`` to the open stream ``file``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
Printer(file, **kwargs).visit(node)
def dumps(node: ast.QASMNode, **kwargs) -> str:
"""Get a string representation of the OpenQASM 3 code representing ``node``.
It is generally expected that ``node`` will be an instance of :class:`.ast.Program`, but this
does not need to be the case.
For more details on the available keyword arguments, see :ref:`printer-kwargs`.
"""
out = io.StringIO()
dump(node, out, **kwargs)
return out.getvalue()
@dataclasses.dataclass
class PrinterState:
"""State object for the print visitor. This is mutated during the visit."""
current_indent: int = 0
"""The current indentation level. This is a non-negative integer; the actual identation string
to be used is defined by the :class:`Printer`."""
skip_next_indent: bool = False
"""This is used to communicate between the different levels of if-else visitors when emitting
chained ``else if`` blocks. The chaining occurs with the next ``if`` if this is set to
``True``."""
@contextlib.contextmanager
def increase_scope(self):
"""Use as a context manager to increase the scoping level of this context inside the
resource block."""
self.current_indent += 1
try:
yield
finally:
self.current_indent -= 1
class Printer(QASMVisitor[PrinterState]):
"""Internal AST-visitor for writing AST nodes out to a stream as valid OpenQASM 3.
This class can be used directly to write multiple nodes to the same stream, potentially with
some manual control fo the state between them.
If subclassing, generally only the specialised ``visit_*`` methods need to be overridden. These
are derived from the base class, and use the name of the relevant :mod:`AST node <.ast>`
verbatim after ``visit_``."""
def __init__(
self,
stream: io.TextIOBase,
*,
indent: str = " ",
chain_else_if: bool = True,
old_measurement: bool = False,
):
"""
Aside from ``stream``, the arguments here are keyword arguments that are common to this
class, :func:`~openqasm3.dump` and :func:`~openqasm3.dumps`.
:param stream: the stream that the output will be written to.
:type stream: io.TextIOBase
:param indent: the string to use as a single indentation level.
:type indent: str, optional (two spaces).
:param chain_else_if: If ``True`` (default), then constructs of the form::
if (x == 0) {
// ...
} else {
if (x == 1) {
// ...
} else {
// ...
}
}
will be collapsed into the equivalent but flatter::
if (x == 0) {
// ...
} else if (x == 1) {
// ...
} else {
// ...
}
:type chain_else_if: bool, optional (``True``)
:param old_measurement: If ``True``, then the OpenQASM 2-style "arrow" measurements will be
used instead of the normal assignments. For example, ``old_measurement=False`` (the
default) will emit ``a = measure b;`` where ``old_measurement=True`` would emit
``measure b -> a;`` instead.
:type old_measurement: bool, optional (``False``).
"""
self.stream = stream
self.indent = indent
self.chain_else_if = chain_else_if
self.old_measurement = old_measurement
def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:
"""Completely visit a node and all subnodes. This is the dispatch entry point; this will
automatically result in the correct specialised visitor getting called.
:param node: The AST node to visit. Usually this will be an :class:`.ast.Program`.
:type node: .ast.QASMNode
:param context: The state object to be used during the visit. If not given, a default
object will be constructed and used.
:type context: PrinterState
"""
if context is None:
context = PrinterState()
return super().visit(node, context)
def _start_line(self, context: PrinterState) -> None:
if context.skip_next_indent:
context.skip_next_indent = False
return
self.stream.write(context.current_indent * self.indent)
def _end_statement(self, context: PrinterState) -> None:
self.stream.write(";\n")
def _end_line(self, context: PrinterState) -> None:
self.stream.write("\n")
def _write_statement(self, line: str, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(line)
self._end_statement(context)
def _visit_sequence(
self,
nodes: Sequence[ast.QASMNode],
context: PrinterState,
*,
start: str = "",
end: str = "",
separator: str,
) -> None:
if start:
self.stream.write(start)
for node in nodes[:-1]:
self.visit(node, context)
self.stream.write(separator)
if nodes:
self.visit(nodes[-1], context)
if end:
self.stream.write(end)
def visit_Program(self, node: ast.Program, context: PrinterState) -> None:
if node.version:
self._write_statement(f"OPENQASM {node.version}", context)
for statement in node.statements:
self.visit(statement, context)
def visit_Include(self, node: ast.Include, context: PrinterState) -> None:
self._write_statement(f'include "{node.filename}"', context)
def visit_ExpressionStatement(
self, node: ast.ExpressionStatement, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.expression, context)
self._end_statement(context)
def visit_QubitDeclaration(self, node: ast.QubitDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.qubit, context)
self._end_statement(context)
def visit_QuantumGateDefinition(
self, node: ast.QuantumGateDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("gate ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ExternDeclaration(self, node: ast.ExternDeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("extern ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self._end_statement(context)
def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None:
self.stream.write(node.name)
def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState) -> None:
self.stream.write(node.op.name)
if properties.precedence(node) >= properties.precedence(node.expression):
self.stream.write("(")
self.visit(node.expression, context)
self.stream.write(")")
else:
self.visit(node.expression, context)
def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState) -> None:
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(f" {node.op.name} ")
if properties.precedence(node.rhs) <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_BitstringLiteral(self, node: ast.BitstringLiteral, context: PrinterState) -> None:
value = bin(node.value)[2:]
if len(value) < node.width:
value = "0" * (node.width - len(value)) + value
self.stream.write(f'"{value}"')
def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState) -> None:
self.stream.write(str(node.value))
def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState) -> None:
self.stream.write("true" if node.value else "false")
def visit_DurationLiteral(self, node: ast.DurationLiteral, context: PrinterState) -> None:
self.stream.write(f"{node.value}{node.unit.name}")
def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:
self.visit(node.name)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
def visit_Cast(self, node: ast.Cast, context: PrinterState) -> None:
self.visit(node.type)
self.stream.write("(")
self.visit(node.argument)
self.stream.write(")")
def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:
self._visit_sequence(node.values, context, start="{", end="}", separator=", ")
def visit_RangeDefinition(self, node: ast.RangeDefinition, context: PrinterState) -> None:
if node.start is not None:
self.visit(node.start, context)
self.stream.write(":")
if node.step is not None:
self.visit(node.step, context)
self.stream.write(":")
if node.end is not None:
self.visit(node.end, context)
def visit_IndexExpression(self, node: ast.IndexExpression, context: PrinterState) -> None:
if properties.precedence(node.collection) < properties.precedence(node):
self.stream.write("(")
self.visit(node.collection, context)
self.stream.write(")")
else:
self.visit(node.collection, context)
self.stream.write("[")
if isinstance(node.index, ast.DiscreteSet):
self.visit(node.index, context)
else:
self._visit_sequence(node.index, context, separator=", ")
self.stream.write("]")
def visit_IndexedIdentifier(self, node: ast.IndexedIdentifier, context: PrinterState) -> None:
self.visit(node.name, context)
for index in node.indices:
self.stream.write("[")
if isinstance(index, ast.DiscreteSet):
self.visit(index, context)
else:
self._visit_sequence(index, context, separator=", ")
self.stream.write("]")
def visit_Concatenation(self, node: ast.Concatenation, context: PrinterState) -> None:
lhs_precedence = properties.precedence(node.lhs)
our_precedence = properties.precedence(node)
rhs_precedence = properties.precedence(node.rhs)
# Concatenation is fully associative, but this package parses the AST by
# arbitrarily making it left-associative (since the design of the AST
# forces us to make a choice). We emit brackets to ensure that the
# round-trip through our printer and parser do not change the AST.
if lhs_precedence < our_precedence:
self.stream.write("(")
self.visit(node.lhs, context)
self.stream.write(")")
else:
self.visit(node.lhs, context)
self.stream.write(" ++ ")
if rhs_precedence <= our_precedence:
self.stream.write("(")
self.visit(node.rhs, context)
self.stream.write(")")
else:
self.visit(node.rhs, context)
def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.visit(node.name, context)
if node.arguments:
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumGateModifier(
self, node: ast.QuantumGateModifier, context: PrinterState
) -> None:
self.stream.write(node.modifier.name)
if node.argument is not None:
self.stream.write("(")
self.visit(node.argument, context)
self.stream.write(")")
def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:
self._start_line(context)
if node.modifiers:
self._visit_sequence(node.modifiers, context, end=" @ ", separator=" @ ")
self.stream.write("gphase(")
self.visit(node.argument, context)
self.stream.write(")")
if node.qubits:
self._visit_sequence(node.qubits, context, start=" ", separator=", ")
self._end_statement(context)
def visit_QuantumMeasurement(self, node: ast.QuantumMeasurement, context: PrinterState) -> None:
self.stream.write("measure ")
self.visit(node.qubit, context)
def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("reset ")
self.visit(node.qubits, context)
self._end_statement(context)
def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("barrier ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_QuantumMeasurementStatement(
self, node: ast.QuantumMeasurementStatement, context: PrinterState
) -> None:
self._start_line(context)
if node.target is None:
self.visit(node.measure, context)
elif self.old_measurement:
self.visit(node.measure, context)
self.stream.write(" -> ")
self.visit(node.target, context)
else:
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.measure, context)
self._end_statement(context)
def visit_ClassicalArgument(self, node: ast.ClassicalArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.name, context)
def visit_ExternArgument(self, node: ast.ExternArgument, context: PrinterState) -> None:
if node.access is not None:
self.stream.write("const " if node.access == ast.AccessControl.const else "mutable ")
self.visit(node.type, context)
def visit_ClassicalDeclaration(
self, node: ast.ClassicalDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
if node.init_expression is not None:
self.stream.write(" = ")
self.visit(node.init_expression)
self._end_statement(context)
def visit_IODeclaration(self, node: ast.IODeclaration, context: PrinterState) -> None:
self._start_line(context)
self.stream.write(f"{node.io_identifier.name} ")
self.visit(node.type)
self.stream.write(" ")
self.visit(node.identifier, context)
self._end_statement(context)
def visit_ConstantDeclaration(
self, node: ast.ConstantDeclaration, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("const ")
self.visit(node.type, context)
self.stream.write(" ")
self.visit(node.identifier, context)
self.stream.write(" = ")
self.visit(node.init_expression, context)
self._end_statement(context)
def visit_IntType(self, node: ast.IntType, context: PrinterState) -> None:
self.stream.write("int")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_UintType(self, node: ast.UintType, context: PrinterState) -> None:
self.stream.write("uint")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_FloatType(self, node: ast.FloatType, context: PrinterState) -> None:
self.stream.write("float")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_ComplexType(self, node: ast.ComplexType, context: PrinterState) -> None:
self.stream.write("complex[")
self.visit(node.base_type, context)
self.stream.write("]")
def visit_AngleType(self, node: ast.AngleType, context: PrinterState) -> None:
self.stream.write("angle")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BitType(self, node: ast.BitType, context: PrinterState) -> None:
self.stream.write("bit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
def visit_BoolType(self, node: ast.BoolType, context: PrinterState) -> None:
self.stream.write("bool")
def visit_ArrayType(self, node: ast.ArrayType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self._visit_sequence(node.dimensions, context, start=", ", end="]", separator=", ")
def visit_ArrayReferenceType(self, node: ast.ArrayReferenceType, context: PrinterState) -> None:
self.stream.write("array[")
self.visit(node.base_type, context)
self.stream.write(", ")
if isinstance(node.dimensions, ast.Expression):
self.stream.write("#dim=")
self.visit(node.dimensions, context)
else:
self._visit_sequence(node.dimensions, context, separator=", ")
self.stream.write("]")
def visit_DurationType(self, node: ast.DurationType, context: PrinterState) -> None:
self.stream.write("duration")
def visit_StretchType(self, node: ast.StretchType, context: PrinterState) -> None:
self.stream.write("stretch")
def visit_CalibrationGrammarDeclaration(
self, node: ast.CalibrationGrammarDeclaration, context: PrinterState
) -> None:
self._write_statement(f'defcalgrammar "{node.name}"', context)
def visit_CalibrationDefinition(
self, node: ast.CalibrationDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("defcal ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
self.stream.write(" ")
self._visit_sequence(node.qubits, context, separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
# At this point we _should_ be deferring to something else to handle formatting the
# calibration grammar statements, but we're neither we nor the AST are set up to do that.
self.stream.write(node.body)
self.stream.write("}")
self._end_line(context)
def visit_SubroutineDefinition(
self, node: ast.SubroutineDefinition, context: PrinterState
) -> None:
self._start_line(context)
self.stream.write("def ")
self.visit(node.name, context)
self._visit_sequence(node.arguments, context, start="(", end=")", separator=", ")
if node.return_type is not None:
self.stream.write(" -> ")
self.visit(node.return_type, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_QuantumArgument(self, node: ast.QuantumArgument, context: PrinterState) -> None:
self.stream.write("qubit")
if node.size is not None:
self.stream.write("[")
self.visit(node.size, context)
self.stream.write("]")
self.stream.write(" ")
self.visit(node.name, context)
def visit_ReturnStatement(self, node: ast.ReturnStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("return")
if node.expression is not None:
self.stream.write(" ")
self.visit(node.expression)
self._end_statement(context)
def visit_BreakStatement(self, node: ast.BreakStatement, context: PrinterState) -> None:
self._write_statement("break", context)
def visit_ContinueStatement(self, node: ast.ContinueStatement, context: PrinterState) -> None:
self._write_statement("continue", context)
def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:
self._write_statement("end", context)
def visit_BranchingStatement(self, node: ast.BranchingStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("if (")
self.visit(node.condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.if_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
if node.else_block:
self.stream.write(" else ")
# Special handling to flatten a perfectly nested structure of
# if {...} else { if {...} else {...} }
# into the simpler
# if {...} else if {...} else {...}
# but only if we're allowed to by our options.
if (
self.chain_else_if
and len(node.else_block) == 1
and isinstance(node.else_block[0], ast.BranchingStatement)
):
context.skip_next_indent = True
self.visit(node.else_block[0], context)
# Don't end the line, because the outer-most `if` block will.
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.else_block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
else:
self._end_line(context)
def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("while (")
self.visit(node.while_condition, context)
self.stream.write(") {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("for ")
self.visit(node.loop_variable, context)
self.stream.write(" in ")
if isinstance(node.set_declaration, ast.RangeDefinition):
self.stream.write("[")
self.visit(node.set_declaration, context)
self.stream.write("]")
else:
self.visit(node.set_declaration, context)
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.block:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DelayInstruction(self, node: ast.DelayInstruction, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("delay[")
self.visit(node.duration, context)
self.stream.write("] ")
self._visit_sequence(node.qubits, context, separator=", ")
self._end_statement(context)
def visit_Box(self, node: ast.Box, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("box")
if node.duration is not None:
self.stream.write("[")
self.visit(node.duration, context)
self.stream.write("]")
self.stream.write(" {")
self._end_line(context)
with context.increase_scope():
for statement in node.body:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:
self.stream.write("durationof(")
if isinstance(node.target, ast.QASMNode):
self.visit(node.target, context)
else:
self.stream.write("{")
self._end_line(context)
with context.increase_scope():
for statement in node.target:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self.stream.write(")")
def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:
self.stream.write("sizeof(")
self.visit(node.target, context)
if node.index is not None:
self.stream.write(", ")
self.visit(node.index)
self.stream.write(")")
def visit_AliasStatement(self, node: ast.AliasStatement, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("let ")
self.visit(node.target, context)
self.stream.write(" = ")
self.visit(node.value, context)
self._end_statement(context)
def visit_ClassicalAssignment(
self, node: ast.ClassicalAssignment, context: PrinterState
) -> None:
self._start_line(context)
self.visit(node.lvalue, context)
self.stream.write(f" {node.op.name} ")
self.visit(node.rvalue, context)
self._end_statement(context)
def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:
self._start_line(context)
self.stream.write("#pragma {")
self._end_line(context)
with context. | ():
for statement in node.statements:
self.visit(statement, context)
self._start_line(context)
self.stream.write("}")
self._end_line(context)
| openqasm__openqasm |
88 | 88-13-32 | inproject | QASMNode | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast. | ):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-21-21 | infile | name | [
"compare",
"default",
"default_factory",
"hash",
"init",
"kw_only",
"metadata",
"name",
"repr",
"type",
"_field_type",
"__annotations__",
"__class__",
"__class_getitem__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__set_name__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field. | ] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-21-63 | infile | name | [
"compare",
"default",
"default_factory",
"hash",
"init",
"kw_only",
"metadata",
"name",
"repr",
"type",
"_field_type",
"__annotations__",
"__class__",
"__class_getitem__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__set_name__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field. | ))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-54-34 | inproject | parse | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3. | (
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-55-22 | commited | dumps | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3. | (
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-62-76 | infile | ast | [
"ast",
"count",
"filename",
"index",
"_asdict",
"_fields",
"_make",
"_replace",
"__add__",
"__annotations__",
"__class__",
"__class_getitem__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example. | )
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-66-27 | commited | dumps | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3. | (openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-66-43 | commited | parse | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3. | (version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-66-69 | commited | strip | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)). | ()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-100-31 | commited | dumps | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3. | (openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-100-47 | commited | parse | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3. | (old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-100-65 | commited | strip | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)). | ()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-259-4 | random | strip | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""". | ()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-334-27 | commited | dumps | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3. | (openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-334-43 | commited | parse | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3. | (input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-334-58 | commited | strip | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)). | ()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-441-27 | commited | dumps | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3. | (openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-441-43 | commited | parse | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3. | (input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-441-71 | commited | strip | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" "). | ()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-467-27 | commited | dumps | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3. | (
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-468-22 | inproject | parse | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3. | (input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-563-20 | inproject | ExpressionStatement | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast. | (
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-564-24 | inproject | BinaryExpression | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast. | (
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-567-32 | inproject | BinaryExpression | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast. | (
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-580-27 | commited | dumps | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3. | (input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-580-41 | commited | strip | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_). | ()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-582-25 | inproject | parse | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3. | (output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-588-21 | inproject | Program | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast. | (
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-591-24 | inproject | Identifier | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast. | ("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-592-24 | inproject | Concatenation | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast. | (
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-593-32 | inproject | Concatenation | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast. | (
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-594-36 | inproject | Identifier | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast. | ("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-595-36 | inproject | Identifier | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast. | ("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-600-20 | inproject | AliasStatement | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast. | (
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-604-32 | inproject | Concatenation | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast. | (
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-605-36 | inproject | Identifier | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast. | ("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-627-32 | inproject | BinaryExpression | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast. | (
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-643-36 | inproject | Identifier | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast. | ("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-677-36 | inproject | Identifier | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast. | ("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-679-36 | inproject | Identifier | [
"AccessControl",
"AliasStatement",
"AngleType",
"annotations",
"ArrayLiteral",
"ArrayReferenceType",
"ArrayType",
"AssignmentOperator",
"BinaryExpression",
"BinaryOperator",
"BitstringLiteral",
"BitType",
"BooleanLiteral",
"BoolType",
"Box",
"BranchingStatement",
"BreakStatement",
"CalibrationDefinition",
"CalibrationGrammarDeclaration",
"Cast",
"ClassicalArgument",
"ClassicalAssignment",
"ClassicalDeclaration",
"ClassicalType",
"ComplexType",
"Concatenation",
"ConstantDeclaration",
"ContinueStatement",
"dataclass",
"DelayInstruction",
"DiscreteSet",
"DurationLiteral",
"DurationOf",
"DurationType",
"EndStatement",
"Enum",
"Expression",
"ExpressionStatement",
"ExternArgument",
"ExternDeclaration",
"field",
"FloatLiteral",
"FloatType",
"ForInLoop",
"FunctionCall",
"GateModifierName",
"Identifier",
"Include",
"IndexedIdentifier",
"IndexElement",
"IndexExpression",
"IntegerLiteral",
"IntType",
"IODeclaration",
"IOKeyword",
"List",
"Optional",
"Pragma",
"Program",
"QASMNode",
"QuantumArgument",
"QuantumBarrier",
"QuantumGate",
"QuantumGateDefinition",
"QuantumGateModifier",
"QuantumMeasurement",
"QuantumMeasurementStatement",
"QuantumPhase",
"QuantumReset",
"QuantumStatement",
"QubitDeclaration",
"RangeDefinition",
"ReturnStatement",
"SizeOf",
"Span",
"Statement",
"StretchType",
"SubroutineDefinition",
"TimeUnit",
"UintType",
"UnaryExpression",
"UnaryOperator",
"Union",
"WhileLoop",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast. | ("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-721-27 | commited | dumps | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3. | (openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-721-43 | commited | parse | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3. | (input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-721-73 | commited | strip | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent). | ()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-730-19 | random | param | [
"annotations",
"approx",
"Cache",
"CallInfo",
"CaptureFixture",
"Class",
"cmdline",
"Collector",
"CollectReport",
"Config",
"console_main",
"deprecated_call",
"Dir",
"Directory",
"DoctestItem",
"ExceptionInfo",
"exit",
"ExitCode",
"fail",
"File",
"fixture",
"FixtureDef",
"FixtureLookupError",
"FixtureRequest",
"freeze_includes",
"Function",
"hookimpl",
"HookRecorder",
"hookspec",
"importorskip",
"Item",
"LineMatcher",
"LogCaptureFixture",
"main",
"mark",
"Mark",
"MarkDecorator",
"MarkGenerator",
"Metafunc",
"Module",
"MonkeyPatch",
"OptionGroup",
"Package",
"param",
"Parser",
"PytestAssertRewriteWarning",
"PytestCacheWarning",
"PytestCollectionWarning",
"PytestConfigWarning",
"PytestDeprecationWarning",
"Pytester",
"PytestExperimentalApiWarning",
"PytestPluginManager",
"PytestRemovedIn9Warning",
"PytestReturnNotNoneWarning",
"PytestUnhandledCoroutineWarning",
"PytestUnhandledThreadExceptionWarning",
"PytestUnknownMarkWarning",
"PytestUnraisableExceptionWarning",
"PytestWarning",
"raises",
"RecordedHookCall",
"register_assert_rewrite",
"RunResult",
"Session",
"set_trace",
"skip",
"Stash",
"StashKey",
"TempdirFactory",
"TempPathFactory",
"Testdir",
"TestReport",
"TestShortLogReport",
"UsageError",
"version_tuple",
"WarningsRecorder",
"warns",
"xfail",
"yield_fixture",
"__all__",
"__doc__",
"__file__",
"__main__",
"__name__",
"__package__",
"__pytestPDB",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest. | ("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-767-27 | commited | dumps | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3. | (openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-767-43 | commited | parse | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3. | (old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-767-83 | commited | strip | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True). | ()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-770-27 | commited | dumps | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3. | (openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-770-43 | commited | parse | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3. | (input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-770-80 | commited | strip | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True). | ()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-852-27 | commited | dumps | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3. | (openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-852-43 | commited | parse | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3. | (input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-852-92 | commited | strip | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False). | ()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-875-27 | commited | dumps | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3. | (openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-875-43 | commited | parse | [
"antlr",
"ast",
"dump",
"dumps",
"parse",
"parser",
"printer",
"properties",
"visitor",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3. | (input_), indent=" ", chain_else_if=True).strip()
assert output == input_
| openqasm__openqasm |
88 | 88-875-91 | commited | strip | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import dataclasses
import pytest
import openqasm3
from openqasm3 import ast
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, ast.QASMNode):
return node
kwargs = {}
no_init = {}
for field in dataclasses.fields(node):
if field.name == "span":
continue
target = kwargs if field.init else no_init
target[field.name] = _remove_spans(getattr(node, field.name))
out = type(node)(**kwargs)
for attribute, value in no_init.items():
setattr(out, attribute, value)
return out
OPERATOR_PRECEDENCE = [
ast.BinaryOperator["||"],
ast.BinaryOperator["&&"],
ast.BinaryOperator["|"],
ast.BinaryOperator["^"],
ast.BinaryOperator["&"],
ast.BinaryOperator["<<"],
ast.BinaryOperator["+"],
ast.BinaryOperator["*"],
ast.BinaryOperator["**"],
]
class TestRoundTrip:
"""All the tests in this class are testing the round-trip properties of the "parse - print -
parse" operation. The test cases all need to be written in the preferred output format of the
printer itself."""
@pytest.mark.parametrize("indent", ["", " ", "\t"], ids=repr)
@pytest.mark.parametrize("chain_else_if", [True, False])
@pytest.mark.parametrize("old_measurement", [True, False])
def test_example_files(self, parsed_example, indent, chain_else_if, old_measurement):
"""Test that the cycle 'parse - print - parse' does not affect the generated AST of the
example files. Printing should just be an exercise in formatting, so should not affect how
subsequent runs parse the file. This also functions as something of a general integration
test, testing much of the basic surface of the language."""
roundtrip_ast = openqasm3.parse(
openqasm3.dumps(
parsed_example.ast,
indent=indent,
chain_else_if=chain_else_if,
old_measurement=old_measurement,
)
)
assert _remove_spans(roundtrip_ast) == _remove_spans(parsed_example.ast)
@pytest.mark.parametrize("version_statement", ["OPENQASM 3;", "OPENQASM 3.0;"])
def test_version(self, version_statement):
output = openqasm3.dumps(openqasm3.parse(version_statement)).strip()
assert output == version_statement
def test_io_declarations(self):
input_ = """
input int a;
input float[64] a;
input complex[float[FLOAT_WIDTH]] a;
output bit b;
output bit[SIZE] b;
output bool b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_include(self):
input_ = 'include "stdgates.inc";'
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_qubit_declarations(self):
input_ = """
qubit q;
qubit[5] q;
qubit[SIZE] q;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
old_input = """
qreg q;
qreg q[5];
qreg q[SIZE];
""".strip()
old_output = openqasm3.dumps(openqasm3.parse(old_input)).strip()
# Note we're testing that we normalise to the new form.
assert input_ == old_output
def test_gate_definition(self):
input_ = """
gate my_gate q {
}
gate my_gate(param) q {
}
gate my_gate(param1, param2) q {
}
gate my_gate q1, q2 {
}
gate my_gate q {
x q;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_extern_declaration(self):
input_ = """
extern f();
extern f() -> bool;
extern f(bool);
extern f(int[32], uint[32]);
extern f(mutable array[complex[float[64]], N_ELEMENTS]) -> int[2 * INT_SIZE];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_declaration(self):
input_ = """
def f() {
}
def f() -> angle[32] {
return pi;
}
def f(int[SIZE] a) {
}
def f(qubit q1, qubit[SIZE] q2) {
}
def f(const array[int[32], 2] a, mutable array[uint, #dim=2] b) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_unary_expression(self):
input_ = """
!a;
-a;
~(a + a);
-a ** 2;
!true;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_binary_expression(self):
input_ = """
a * b;
a / b;
1 + 2;
1 - 2;
(1 + 2) * 3;
2 ** 8;
a << 1;
a >> b;
2 < 3;
3 >= 2;
a == b;
a != b;
a & b;
a | b;
a ^ b;
a && b;
a || b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_assignment(self):
input_ = """
a = 1;
a = 2 * b;
a = f(4);
a += 1;
a -= a * 0.5;
a *= 2.0;
a /= 1.5;
a **= 2;
a <<= 1;
a >>= 1;
a |= f(2, 3);
a &= "101001";
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_index_expression(self):
input_ = """
a[0];
a[{1, 2, 3}];
a[0][0];
a[1:2][0];
a[0][1:2];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_literal(self):
input_ = """
1;
2.0;
true;
false;
"1010";
"01010";
-1;
1.0ms;
1.0ns;
2.0s;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_declaration(self):
input_ = """
bool x = true;
bit x;
bit[SIZE] x;
int x = 2;
int[32] x = -5;
uint x = 0;
uint[16] x;
angle x;
angle[SIZE] x;
float x = 2.0;
float[SIZE * 2] x = 4.0;
complex[float[64]] x;
duration a = 1.0us;
stretch b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_const_declaration(self):
input_ = """
const bool x = true;
const int x = 2;
const int[32] x = -5;
const uint x = 0;
const uint[16] x = 0;
const angle x = pi;
const angle[SIZE] x = pi / 8;
const float x = 2.0;
const float[SIZE * 2] x = 4.0;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_array_initializer(self):
input_ = """
array[int, 2] a = {1, 2};
array[float[64], 2, 2] a = {{1.0, 0.0}, {0.0, 1.0}};
array[angle[32], 2] a = {pi, pi / 8};
array[uint[16], 4, 4] a = {b, {1, 2, 3, 4}};
array[bool, 2, 2] a = b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_alias(self):
input_ = """
let q = a ++ b;
let q = a[1:2];
let q = a[{0, 2, 3}] ++ a[1:1] ++ a[{4, 5}];
let q = a;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_function_call(self):
input_ = """
f(1, 2, 3);
f();
f(a, b + c, a * b / c);
f(f(a));
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_call(self):
input_ = """
h q;
h q[0];
gphase(pi);
U(1, 2, 3) q;
U(1, 2, 3) q[0];
my_gate a, b[0:2], c;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_gate_modifiers(self):
input_ = """
ctrl @ U(1, 2, 3) a, b;
ctrl(1) @ x a, b[0];
negctrl @ U(1, 2, 3) a[0:2], b;
negctrl(2) @ h a, b, c;
pow(2) @ h a;
ctrl @ gphase(pi / 2) a, b;
inv @ h a;
inv @ ctrl @ x a, b;
ctrl(1) @ inv @ x a, b;
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_cast(self):
input_ = """
int(a);
int[32](2.0);
int[SIZE](bitstring);
uint[16 + 16](a);
bit[SIZE](pi);
bool(i);
complex[float[64]](2.0);
complex[float](2.5);
float[32](1);
float(2.0);
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_for_loop(self):
input_ = """
for i in [0:2] {
a += 1;
}
for i in [a:b] {
a += 1;
}
for i in [a:2 * b:c] {
a += 1;
}
for i in {1, 2, 3} {
a += 1;
}
for i in {2 * j, 2 + 3 / 4, j + j} {
a += 1;
}
for i in j {
a += 1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_while_loop(self):
input_ = """
while (i) {
x $0;
i -= 1;
}
while (i == 0) {
x $0;
i -= 1;
}
while (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_if(self):
input_ = """
if (i) {
x $0;
}
if (true) {
x $0;
}
if (2 + 3 == 5) {
x $0;
}
if (!true) {
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else(self):
input_ = """
if (true) {
} else {
x $0;
}
if (true) {
} else {
x $0;
a = b + 2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
x $0;
} else if (i == 2) {
} else {
x $1;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_jumps(self):
input_ = """
while (true) {
break;
continue;
end;
}
def f() {
return;
}
def f() -> int[32] {
return 2 + 3;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_measurement(self):
input_ = """
measure q;
measure $0;
measure q[0];
measure q[1:3];
c = measure q;
c = measure $0;
c = measure q[0];
c = measure q[1:3];
def f() {
return measure q;
}
def f() {
return measure $0;
}
def f() {
return measure q[0];
}
def f() {
return measure q[1:3];
}
""".strip()
output = openqasm3.dumps(
openqasm3.parse(input_), indent=" ", old_measurement=False
).strip()
assert output == input_
def test_reset(self):
input_ = """
reset q;
reset $0;
reset q[0];
reset q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_barrier(self):
input_ = """
barrier q;
barrier $0;
barrier q[0];
barrier q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_delay(self):
input_ = """
delay[50.0ns] q;
delay[50.0ns] $0;
delay[50.0ns] q[0];
delay[50.0ns] q[1:3];
delay[2 * SIZE] q;
delay[2 * SIZE] $0;
delay[2 * SIZE] q[0];
delay[2 * SIZE] q[1:3];
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
def test_box(self):
input_ = """
box {
x $0;
}
box[100.0ns] {
x $0;
}
box[a + b] {
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_duration_of(self):
input_ = """
duration a = durationof({
x $0;
ctrl @ x $1, $2;
});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ").strip()
assert output == input_
def test_pragma(self):
input_ = """
#pragma {
val1;
val2;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_)).strip()
assert output == input_
class TestExpression:
"""Test more specific features and properties of the printer when outputting expressions."""
@pytest.mark.parametrize(
"operator", [op for op in ast.BinaryOperator if op != ast.BinaryOperator["**"]]
)
def test_associativity_binary(self, operator):
"""Test that the associativity of binary expressions is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.Identifier("b"),
),
op=operator,
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=operator,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=operator,
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
a {operator.name} b {operator.name} c;
a {operator.name} (b {operator.name} c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Parser cannot handle bracketed concatenations")
def test_associativity_concatenation(self):
"""The associativity of concatenation is not fully defined by the grammar or specification,
but the printer assumes left-associativity for now."""
input_ = ast.Program(
statements=[
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Identifier("b"),
),
rhs=ast.Identifier("c"),
),
),
ast.AliasStatement(
ast.Identifier("q"),
ast.Concatenation(
lhs=ast.Identifier("a"),
rhs=ast.Concatenation(
lhs=ast.Identifier("b"),
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = """
let q = a ++ b ++ c;
let q = a ++ (b ++ c);
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.xfail(reason="Currently power is still left-associative in the ANTLR grammar")
def test_associativity_power(self):
"""Test that the right-associativity of the power expression is respected in the output."""
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("b"),
),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=ast.BinaryOperator["**"],
rhs=ast.BinaryExpression(
lhs=ast.Identifier("b"),
op=ast.BinaryOperator["**"],
rhs=ast.Identifier("c"),
),
),
),
],
)
expected = f"""
(a ** b) ** c;
a ** b ** c;
""".strip()
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
@pytest.mark.parametrize(
["lower", "higher"],
[
(lower, higher)
for i, lower in enumerate(OPERATOR_PRECEDENCE[:-1])
for higher in OPERATOR_PRECEDENCE[i + 1 :]
],
)
def test_precedence(self, lower, higher):
input_ = ast.Program(
statements=[
ast.ExpressionStatement(
ast.BinaryExpression(
lhs=ast.BinaryExpression(
lhs=ast.Identifier("a"),
op=lower,
rhs=ast.Identifier("b"),
),
op=higher,
rhs=ast.BinaryExpression(
lhs=ast.Identifier("c"),
op=lower,
rhs=ast.Identifier("d"),
),
),
),
],
)
expected = f"(a {lower.name} b) {higher.name} (c {lower.name} d);"
output = openqasm3.dumps(input_).strip()
assert output == expected
assert openqasm3.parse(output) == input_
class TestOptions:
"""Test the various keyword arguments to the exporter have the desired effects."""
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
def test_indent(self, indent):
input_ = f"""
def f(int[32] a) -> bool {{
{indent}return a == a;
}}
gate g(param) q {{
{indent}h q;
}}
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
box {{
{indent}x $0;
}}
durationof({{
{indent}x $0;
}});
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
@pytest.mark.parametrize("indent", ["", " ", "\t", " "], ids=repr)
@pytest.mark.parametrize(
["outer_start", "outer_end", "allow_classical"],
[
pytest.param("gate f q {", "}", False, id="gate"),
pytest.param("durationof({", "});", False, id="durationof"),
pytest.param("def f() {", "}", True, id="function"),
pytest.param("if (true) {", "}", True, id="if"),
pytest.param("if (true) {\n} else {", "}", True, id="else"),
pytest.param("box[1.0ms] {", "}", False, id="box"),
],
)
def test_indent_nested(self, indent, outer_start, outer_end, allow_classical):
classicals = f"""
for i in [0:2] {{
{indent}true;
}}
while (i) {{
{indent}i -= 1;
}}
if (i) {{
{indent}x $0;
}} else {{
{indent}x $1;
}}
durationof({{
{indent}x $0;
}});
""".strip()
quantums = f"""
box {{
{indent}x $0;
}}
""".strip()
lines = quantums.splitlines()
if allow_classical:
lines.extend(classicals.splitlines())
input_ = outer_start + "\n" + "\n".join(indent + line for line in lines) + "\n" + outer_end
output = openqasm3.dumps(openqasm3.parse(input_), indent=indent).strip()
assert output == input_
def test_old_measurement(self):
old_input = "measure q -> c;"
output = openqasm3.dumps(openqasm3.parse(old_input), old_measurement=True).strip()
assert output == old_input
input_ = "c = measure q;"
output = openqasm3.dumps(openqasm3.parse(input_), old_measurement=True).strip()
assert output == old_input
def test_chain_else_if(self):
input_ = """
if (i == 0) {
} else if (i == 1) {
}
if (i == 0) {
} else if (i == 1) {
} else {
x $0;
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
}
if (i == 0) {
} else if (i == 1) {
} else if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True).strip()
assert output == input_
def test_no_chain_else_if(self):
input_ = """
if (i == 0) {
} else {
if (i == 1) {
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
x $0;
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
}
}
}
if (i == 0) {
} else {
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
}
x $0;
}
}
}
if (i == 0) {
} else {
if (i == 2) {
x $0;
} else {
x $0;
}
x $0;
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=False).strip()
assert output == input_
def test_chain_else_if_only_applies_to_else_if(self):
input_ = """
if (i) {
} else {
x $1;
}
if (i) {
} else {
for j in [0:1] {
}
}
if (i) {
} else {
x $0;
if (!i) {
} else {
x $1;
}
}
""".strip()
output = openqasm3.dumps(openqasm3.parse(input_), indent=" ", chain_else_if=True). | ()
assert output == input_
| openqasm__openqasm |
93 | 93-24-12 | inproject | info | [
"BrowserConfig",
"colorLog",
"debug",
"error",
"file_dir",
"info",
"ins",
"inspect",
"logger",
"now_time",
"os",
"printf",
"report_dir",
"Seldom",
"stack_t",
"sys",
"time",
"warn",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log. | ("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-34-19 | inproject | driver | [
"base_url",
"debug",
"driver",
"mro",
"timeout",
"__annotations__",
"__base__",
"__bases__",
"__basicsize__",
"__call__",
"__class__",
"__delattr__",
"__dict__",
"__dictoffset__",
"__dir__",
"__doc__",
"__eq__",
"__flags__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__instancecheck__",
"__itemsize__",
"__module__",
"__mro__",
"__name__",
"__ne__",
"__new__",
"__prepare__",
"__qualname__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__",
"__subclasscheck__",
"__subclasses__",
"__text_signature__",
"__weakrefoffset__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.dri | Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-34-73 | inproject | install | [
"driver",
"install",
"__init__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().ins |
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-36-16 | inproject | info | [
"BrowserConfig",
"colorLog",
"debug",
"error",
"file_dir",
"info",
"ins",
"inspect",
"logger",
"now_time",
"os",
"printf",
"report_dir",
"Seldom",
"stack_t",
"sys",
"time",
"warn",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.inf | {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-37-19 | inproject | driver | [
"base_url",
"debug",
"driver",
"mro",
"timeout",
"__annotations__",
"__base__",
"__bases__",
"__basicsize__",
"__call__",
"__class__",
"__delattr__",
"__dict__",
"__dictoffset__",
"__dir__",
"__doc__",
"__eq__",
"__flags__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__instancecheck__",
"__itemsize__",
"__module__",
"__mro__",
"__name__",
"__ne__",
"__new__",
"__prepare__",
"__qualname__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__",
"__subclasscheck__",
"__subclasses__",
"__text_signature__",
"__weakrefoffset__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver | elf.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-37-35 | inproject | url | [
"accept",
"alert",
"clear",
"click",
"click_and_hold",
"close",
"dismiss",
"double_click",
"element_screenshot",
"enter",
"find",
"find_text",
"max_window",
"move_to_click",
"move_to_element",
"open",
"quit",
"refresh",
"right_click",
"screenshots",
"select",
"set_window",
"sleep",
"submit",
"switch_to_frame",
"switch_to_frame_out",
"switch_to_window",
"type",
"url",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
| else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-39-16 | inproject | info | [
"BrowserConfig",
"colorLog",
"debug",
"error",
"file_dir",
"info",
"ins",
"inspect",
"logger",
"now_time",
"os",
"printf",
"report_dir",
"Seldom",
"stack_t",
"sys",
"time",
"warn",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info(" | ".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-40-19 | inproject | driver | [
"base_url",
"debug",
"driver",
"mro",
"timeout",
"__annotations__",
"__base__",
"__bases__",
"__basicsize__",
"__call__",
"__class__",
"__delattr__",
"__dict__",
"__dictoffset__",
"__dir__",
"__doc__",
"__eq__",
"__flags__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__instancecheck__",
"__itemsize__",
"__module__",
"__mro__",
"__name__",
"__ne__",
"__new__",
"__prepare__",
"__qualname__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__",
"__subclasscheck__",
"__subclasses__",
"__text_signature__",
"__weakrefoffset__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.ge |
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-68-41 | inproject | get_elements | [
"by",
"find_elem_info",
"find_elem_warn",
"get_elements",
"info",
"show_element",
"value",
"warn",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_eleme | web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-70-12 | inproject | info | [
"BrowserConfig",
"colorLog",
"debug",
"error",
"file_dir",
"info",
"ins",
"inspect",
"logger",
"now_time",
"os",
"printf",
"report_dir",
"Seldom",
"stack_t",
"sys",
"time",
"warn",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π f | {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-82-17 | inproject | show_element | [
"by",
"find_elem_info",
"find_elem_warn",
"get_elements",
"info",
"show_element",
"value",
"warn",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(ele | og.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-83-12 | inproject | info | [
"BrowserConfig",
"colorLog",
"debug",
"error",
"file_dir",
"info",
"ins",
"inspect",
"logger",
"now_time",
"os",
"printf",
"report_dir",
"Seldom",
"stack_t",
"sys",
"time",
"warn",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} | .".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-98-12 | non_informative | info | [
"BrowserConfig",
"colorLog",
"debug",
"error",
"file_dir",
"info",
"ins",
"inspect",
"logger",
"now_time",
"os",
"printf",
"report_dir",
"Seldom",
"stack_t",
"sys",
"time",
"warn",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
| Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-129-38 | inproject | ENTER | [
"ADD",
"ALT",
"ARROW_DOWN",
"ARROW_LEFT",
"ARROW_RIGHT",
"ARROW_UP",
"BACK_SPACE",
"BACKSPACE",
"CANCEL",
"CLEAR",
"COMMAND",
"CONTROL",
"DECIMAL",
"DELETE",
"DIVIDE",
"DOWN",
"END",
"ENTER",
"EQUALS",
"ESCAPE",
"F1",
"F10",
"F11",
"F12",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"HELP",
"HOME",
"INSERT",
"LEFT",
"LEFT_ALT",
"LEFT_CONTROL",
"LEFT_SHIFT",
"META",
"mro",
"MULTIPLY",
"NULL",
"NUMPAD0",
"NUMPAD1",
"NUMPAD2",
"NUMPAD3",
"NUMPAD4",
"NUMPAD5",
"NUMPAD6",
"NUMPAD7",
"NUMPAD8",
"NUMPAD9",
"PAGE_DOWN",
"PAGE_UP",
"PAUSE",
"RETURN",
"RIGHT",
"SEMICOLON",
"SEPARATOR",
"SHIFT",
"SPACE",
"SUBTRACT",
"TAB",
"UP",
"ZENKAKU_HANKAKU",
"__annotations__",
"__base__",
"__bases__",
"__basicsize__",
"__call__",
"__class__",
"__delattr__",
"__dict__",
"__dictoffset__",
"__dir__",
"__doc__",
"__eq__",
"__flags__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__instancecheck__",
"__itemsize__",
"__module__",
"__mro__",
"__name__",
"__ne__",
"__new__",
"__prepare__",
"__qualname__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__",
"__subclasscheck__",
"__subclasses__",
"__text_signature__",
"__weakrefoffset__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
| f move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-139-12 | inproject | info | [
"BrowserConfig",
"colorLog",
"debug",
"error",
"file_dir",
"info",
"ins",
"inspect",
"logger",
"now_time",
"os",
"printf",
"report_dir",
"Seldom",
"stack_t",
"sys",
"time",
"warn",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element a | lick.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-140-28 | inproject | driver | [
"base_url",
"debug",
"driver",
"mro",
"timeout",
"__annotations__",
"__base__",
"__bases__",
"__basicsize__",
"__call__",
"__class__",
"__delattr__",
"__dict__",
"__dictoffset__",
"__dir__",
"__doc__",
"__eq__",
"__flags__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__instancecheck__",
"__itemsize__",
"__module__",
"__mro__",
"__name__",
"__ne__",
"__new__",
"__prepare__",
"__qualname__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__",
"__subclasscheck__",
"__subclasses__",
"__text_signature__",
"__weakrefoffset__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).c | lem).perform()
return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-140-36 | inproject | move_to_element | [
"click",
"click_and_hold",
"context_click",
"double_click",
"drag_and_drop",
"drag_and_drop_by_offset",
"key_down",
"key_up",
"move_by_offset",
"move_to_element",
"move_to_element_with_offset",
"pause",
"perform",
"release",
"reset_actions",
"scroll_by_amount",
"scroll_from_origin",
"scroll_to_element",
"send_keys",
"send_keys_to_element",
"w3c_actions",
"_driver",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(ele | return self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |
93 | 93-140-58 | inproject | click | [
"click",
"click_and_hold",
"context_click",
"double_click",
"drag_and_drop",
"drag_and_drop_by_offset",
"key_down",
"key_up",
"move_by_offset",
"move_to_element",
"move_to_element_with_offset",
"pause",
"perform",
"release",
"reset_actions",
"scroll_by_amount",
"scroll_from_origin",
"scroll_to_element",
"send_keys",
"send_keys_to_element",
"w3c_actions",
"_driver",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # coding=utf-8
import os
import time
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumWebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from seldom.logging import log
from seldom.running.config import Seldom
from seldom.utils.webdriver_manager_extend import ChromeDriverManager
from seldom.webdriver import WebElement
__all__ = ["Case"]
class Case(object):
"""
Webdriver Basic method chaining
Write test cases quickly.
"""
def __init__(self, url: str = None, desc: str = None):
self.url = url
log.info("π Test Case: {}".format(desc))
def open(self, url: str = None):
"""
open url.
Usage:
open("https://www.baidu.com")
"""
if isinstance(Seldom.driver, SeleniumWebDriver) is False:
Seldom.driver = Chrome(executable_path=ChromeDriverManager().install())
if self.url is not None:
log.info("π {}".format(self.url))
Seldom.driver.get(self.url)
else:
log.info("π {}".format(url))
Seldom.driver.get(url)
return self
def max_window(self):
"""
Set browser window maximized.
Usage:
max_window()
"""
Seldom.driver.maximize_window()
return self
def set_window(self, wide: int = 0, high: int = 0):
"""
Set browser window wide and high.
Usage:
.set_window(wide,high)
"""
Seldom.driver.set_window_size(wide, high)
return self
def find(self, css: str, index: int = 0):
"""
find element
"""
web_elem = WebElement(css=css)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {info}.".format(info=web_elem.info))
return self
def find_text(self, text: str, index: int = 0):
"""
find link text
Usage:
find_text("ζ°ι»")
"""
web_elem = WebElement(link_text=text)
Seldom.element = elem = web_elem.get_elements(index)
web_elem.show_element(elem)
log.info("π find {} text.".format(web_elem.info))
return self
def type(self, text):
"""
type text.
"""
log.info(f"β
input '{text}'.")
Seldom.element.send_keys(text)
return self
def click(self):
"""
click.
"""
log.info("β
click.")
Seldom.element.click()
return self
def clear(self):
"""
clear input.
Usage:
clear()
"""
log.info("β
clear.")
Seldom.element.clear()
return self
def submit(self):
"""
submit input
Usage:
submit()
"""
log.info("β
clear.")
Seldom.element.submit()
return self
def enter(self):
"""
enter.
Usage:
enter()
"""
log.info("β
enter.")
Seldom.element.send_keys(Keys.ENTER)
return self
def move_to_click(self):
"""
Moving the mouse to the middle of an element. and click element.
Usage:
move_to_click()
"""
elem = Seldom.element
log.info("β
Move to the element and click.")
ActionChains(Seldom.driver).move_to_element(elem).click(elem).perform()
r | self
def right_click(self):
"""
Right click element.
Usage:
right_click()
"""
elem = Seldom.element
log.info("β
right click.")
ActionChains(Seldom.driver).context_click(elem).perform()
return self
def move_to_element(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
move to element.")
ActionChains(Seldom.driver).move_to_element(elem).perform()
return self
def click_and_hold(self):
"""
Mouse over the element.
Usage:
move_to_element()
"""
elem = Seldom.element
log.info("β
click and hold.")
ActionChains(Seldom.driver).click_and_hold(elem).perform()
return self
def double_click(self):
"""
Double click element.
Usage:
double_click()
"""
elem = Seldom.element
log.info("β
double click.")
ActionChains(Seldom.driver).double_click(elem).perform()
return self
def close(self):
"""
Closes the current window.
Usage:
close()
"""
Seldom.driver.close()
return self
def quit(self):
"""
Quit the driver and close all the windows.
Usage:
quit()
"""
Seldom.driver.quit()
return self
def refresh(self):
"""
Refresh the current page.
Usage:
refresh()
"""
log.info("ποΈ refresh page.")
Seldom.driver.refresh()
return self
def alert(self):
"""
get alert.
Usage:
alert()
"""
log.info("β
alert.")
Seldom.alert = Seldom.driver.switch_to.alert
return self
def accept(self):
"""
Accept warning box.
Usage:
alert().accept()
"""
log.info("β
accept alert.")
Seldom.alert.accept()
return self
def dismiss(self):
"""
Dismisses the alert available.
Usage:
alert().dismiss()
"""
log.info("β
dismiss alert.")
Seldom.driver.switch_to.alert.dismiss()
return self
def switch_to_frame(self):
"""
Switch to the specified frame.
Usage:
switch_to_frame()
"""
elem = Seldom.element
log.info("β
switch to frame.")
Seldom.driver.switch_to.frame(elem)
return self
def switch_to_frame_out(self):
"""
Returns the current form machine form at the next higher level.
Corresponding relationship with switch_to_frame () method.
Usage:
switch_to_frame_out()
"""
log.info("β
switch to frame out.")
Seldom.driver.switch_to.default_content()
return self
def switch_to_window(self, window: int):
"""
Switches focus to the specified window.
:Args:
- window: window index. 1 represents a newly opened window (0 is the first one)
:Usage:
switch_to_window(1)
"""
log.info("β
switch to the {} window.".format(str(window)))
all_handles = Seldom.driver.window_handles
Seldom.driver.switch_to.window(all_handles[window])
return self
def screenshots(self, file_path: str = None):
"""
Saves a screenshots of the current window to a PNG image file.
Usage:
screenshots()
screenshots('/Screenshots/foo.png')
"""
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ screenshot -> ({file_path}).")
Seldom.driver.save_screenshot(file_path)
else:
log.info("π·οΈ screenshot -> HTML report.")
self.images.append(Seldom.driver.get_screenshot_as_base64())
return self
def element_screenshot(self, file_path: str = None):
"""
Saves a element screenshot of the element to a PNG image file.
Usage:
element_screenshot()
element_screenshot(file_path='/Screenshots/foo.png')
"""
elem = Seldom.element
if file_path is None:
img_dir = os.path.join(os.getcwd(), "reports", "images")
if os.path.exists(img_dir) is False:
os.mkdir(img_dir)
file_path = os.path.join(img_dir, str(time.time()).split(".")[0] + ".png")
if Seldom.debug is True:
log.info(f"π·οΈ element screenshot -> ({file_path}).")
elem.screenshot(file_path)
else:
log.info("π·οΈ element screenshot -> HTML Report.")
self.images.append(elem.screenshot_as_base64)
return self
def select(self, value: str = None, text: str = None, index: int = None):
"""
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
then an UnexpectedTagNameException is thrown.
:Args:
- css - element SELECT element to wrap
- value - The value to match against
Usage:
<select name="NR" id="nr">
<option value="10" selected="">ζ―ι‘΅ζΎη€Ί10ζ‘</option>
<option value="20">ζ―ι‘΅ζΎη€Ί20ζ‘</option>
<option value="50">ζ―ι‘΅ζΎη€Ί50ζ‘</option>
</select>
select(value='20')
select(text='ζ―ι‘΅ζΎη€Ί20ζ‘')
select(index=2)
"""
elem = Seldom.element
log.info("β
select option.")
if value is not None:
Select(elem).select_by_value(value)
elif text is not None:
Select(elem).select_by_visible_text(text)
elif index is not None:
Select(elem).select_by_index(index)
else:
raise ValueError(
'"value" or "text" or "index" options can not be all empty.')
return self
def sleep(self, sec: int):
"""
Usage:
self.sleep(seconds)
"""
log.info("π€οΈ sleep: {}s.".format(str(sec)))
time.sleep(sec)
return self
| seldomqa__seldom |