Skip to content

Commit

Permalink
Add definition of Store instruction
Browse files Browse the repository at this point in the history
This does not yet add the implementation of `QuantumCircuit.store`,
which will come later as part of expanding the full API of
`QuantumCircuit` to be able to support these runtime variables.

The `is_lvalue` helper is added generally to the `classical.expr` module
because it's generally useful, while `types.cast_kind` is moved from
being a private method in `expr` to a public-API function so `Store` can
use it.  These now come with associated unit tests.
  • Loading branch information
jakelishman committed Oct 2, 2023
1 parent c95b99c commit c619ef9
Show file tree
Hide file tree
Showing 10 changed files with 348 additions and 47 deletions.
2 changes: 2 additions & 0 deletions qiskit/circuit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@
Operation
EquivalenceLibrary
SingletonGate
Store
Control Flow Operations
-----------------------
Expand Down Expand Up @@ -375,6 +376,7 @@
from .delay import Delay
from .measure import Measure
from .reset import Reset
from .store import Store
from .parameter import Parameter
from .parametervector import ParameterVector
from .parameterexpression import ParameterExpression
Expand Down
8 changes: 7 additions & 1 deletion qiskit/circuit/classical/expr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,11 @@
suitable "key" functions to do the comparison.
.. autofunction:: structurally_equivalent
Some expressions have associated memory locations with them, and some may be purely temporaries.
You can use :func:`is_lvalue` to determine whether an expression has such a memory backing.
.. autofunction:: is_lvalue
"""

__all__ = [
Expand All @@ -171,6 +176,7 @@
"ExprVisitor",
"iter_vars",
"structurally_equivalent",
"is_lvalue",
"lift",
"cast",
"bit_not",
Expand All @@ -190,7 +196,7 @@
]

from .expr import Expr, Var, Value, Cast, Unary, Binary
from .visitors import ExprVisitor, iter_vars, structurally_equivalent
from .visitors import ExprVisitor, iter_vars, structurally_equivalent, is_lvalue
from .constructors import (
lift,
cast,
Expand Down
52 changes: 7 additions & 45 deletions qiskit/circuit/classical/expr/constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,65 +35,27 @@
"lift_legacy_condition",
]

import enum
import typing

from .expr import Expr, Var, Value, Unary, Binary, Cast
from ..types import CastKind, cast_kind
from .. import types

if typing.TYPE_CHECKING:
import qiskit


class _CastKind(enum.Enum):
EQUAL = enum.auto()
"""The two types are equal; no cast node is required at all."""
IMPLICIT = enum.auto()
"""The 'from' type can be cast to the 'to' type implicitly. A ``Cast(implicit=True)`` node is
the minimum required to specify this."""
LOSSLESS = enum.auto()
"""The 'from' type can be cast to the 'to' type explicitly, and the cast will be lossless. This
requires a ``Cast(implicit=False)`` node, but there's no danger from inserting one."""
DANGEROUS = enum.auto()
"""The 'from' type has a defined cast to the 'to' type, but depending on the value, it may lose
data. A user would need to manually specify casts."""
NONE = enum.auto()
"""There is no casting permitted from the 'from' type to the 'to' type."""


def _uint_cast(from_: types.Uint, to_: types.Uint, /) -> _CastKind:
if from_.width == to_.width:
return _CastKind.EQUAL
if from_.width < to_.width:
return _CastKind.LOSSLESS
return _CastKind.DANGEROUS


_ALLOWED_CASTS = {
(types.Bool, types.Bool): lambda _a, _b, /: _CastKind.EQUAL,
(types.Bool, types.Uint): lambda _a, _b, /: _CastKind.LOSSLESS,
(types.Uint, types.Bool): lambda _a, _b, /: _CastKind.IMPLICIT,
(types.Uint, types.Uint): _uint_cast,
}


def _cast_kind(from_: types.Type, to_: types.Type, /) -> _CastKind:
if (coercer := _ALLOWED_CASTS.get((from_.kind, to_.kind))) is None:
return _CastKind.NONE
return coercer(from_, to_)


def _coerce_lossless(expr: Expr, type: types.Type) -> Expr:
"""Coerce ``expr`` to ``type`` by inserting a suitable :class:`Cast` node, if the cast is
lossless. Otherwise, raise a ``TypeError``."""
kind = _cast_kind(expr.type, type)
if kind is _CastKind.EQUAL:
kind = cast_kind(expr.type, type)
if kind is CastKind.EQUAL:
return expr
if kind is _CastKind.IMPLICIT:
if kind is CastKind.IMPLICIT:
return Cast(expr, type, implicit=True)
if kind is _CastKind.LOSSLESS:
if kind is CastKind.LOSSLESS:
return Cast(expr, type, implicit=False)
if kind is _CastKind.DANGEROUS:
if kind is CastKind.DANGEROUS:
raise TypeError(f"cannot cast '{expr}' to '{type}' without loss of precision")
raise TypeError(f"no cast is defined to take '{expr}' to '{type}'")

Expand Down Expand Up @@ -198,7 +160,7 @@ def cast(operand: typing.Any, type: types.Type, /) -> Expr:
Cast(Value(5, types.Uint(32)), types.Uint(8), implicit=False)
"""
operand = lift(operand)
if _cast_kind(operand.type, type) is _CastKind.NONE:
if cast_kind(operand.type, type) is CastKind.NONE:
raise TypeError(f"cannot cast '{operand}' to '{type}'")
return Cast(operand, type)

Expand Down
63 changes: 63 additions & 0 deletions qiskit/circuit/classical/expr/visitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,66 @@ def structurally_equivalent(
True
"""
return left.accept(_StructuralEquivalenceImpl(right, left_var_key, right_var_key))


class _IsLValueImpl(ExprVisitor[bool]):
__slots__ = ()

def visit_var(self, node, /):
return True

def visit_value(self, node, /):
return False

def visit_unary(self, node, /):
return False

def visit_binary(self, node, /):
return False

def visit_cast(self, node, /):
return False


_IS_LVALUE = _IsLValueImpl()


def is_lvalue(node: expr.Expr, /) -> bool:
"""Return whether this expression can be used in l-value positions, that is, whether it has a
well-defined location in memory, such as one that might be writeable.
Being an l-value is a necessary but not sufficient for this location to be writeable; it is
permissible that a larger object containing this memory location may not allow writing from
the scope that attempts to write to it. This would be an access property of the containing
program, however, and not an inherent property of the expression system.
Examples:
Literal values are never l-values; there's no memory location associated with (for example)
the constant ``1``::
>>> from qiskit.circuit.classical import expr
>>> expr.is_lvalue(expr.lift(2))
False
:class:`~.expr.Var` nodes are always l-values, because they always have some associated
memory location::
>>> from qiskit.circuit.classical import types
>>> from qiskit.circuit import Clbit
>>> expr.is_lvalue(expr.Var.new("a", types.Bool()))
True
>>> expr.is_lvalue(expr.lift(Clbit()))
True
Currently there are no unary or binary operations on variables that can produce an l-value
expression, but it is likely in the future that some sort of "indexing" operation will be
added, which could produce l-values::
>>> a = expr.Var.new("a", types.Uint(8))
>>> b = expr.Var.new("b", types.Uint(8))
>>> expr.is_lvalue(a) and expr.is_lvalue(b)
True
>>> expr.is_lvalue(expr.bit_and(a, b))
False
"""
return node.accept(_IS_LVALUE)
27 changes: 26 additions & 1 deletion qiskit/circuit/classical/types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
Typing (:mod:`qiskit.circuit.classical.types`)
==============================================
Representation
==============
The type system of the expression tree is exposed through this module. This is inherently linked to
the expression system in the :mod:`~.classical.expr` module, as most expressions can only be
Expand All @@ -41,11 +43,18 @@
Note that :class:`Uint` defines a family of types parametrised by their width; it is not one single
type, which may be slightly different to the 'classical' programming languages you are used to.
Working with types
==================
There are some functions on these types exposed here as well. These are mostly expected to be used
only in manipulations of the expression tree; users who are building expressions using the
:ref:`user-facing construction interface <circuit-classical-expressions-expr-construction>` should
not need to use these.
Partial ordering of types
-------------------------
The type system is equipped with a partial ordering, where :math:`a < b` is interpreted as
":math:`a` is a strict subtype of :math:`b`". Note that the partial ordering is a subset of the
directed graph that describes the allowed explicit casting operations between types. The partial
Expand All @@ -66,6 +75,20 @@
.. autofunction:: is_subtype
.. autofunction:: is_supertype
.. autofunction:: greater
Casting between types
---------------------
It is common to need to cast values of one type to another type. The casting rules for this are
embedded into the :mod:`types` module. You can query the casting kinds using :func:`cast_kind`:
.. autofunction:: cast_kind
The return values from this function are an enumeration explaining the types of cast that are
allowed from the left type to the right type.
.. autoclass:: CastKind
"""

__all__ = [
Expand All @@ -77,7 +100,9 @@
"is_subtype",
"is_supertype",
"greater",
"CastKind",
"cast_kind",
]

from .types import Type, Bool, Uint
from .ordering import Ordering, order, is_subtype, is_supertype, greater
from .ordering import Ordering, order, is_subtype, is_supertype, greater, CastKind, cast_kind
59 changes: 59 additions & 0 deletions qiskit/circuit/classical/types/ordering.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
"is_supertype",
"order",
"greater",
"CastKind",
"cast_kind",
]

import enum
Expand Down Expand Up @@ -161,3 +163,60 @@ def greater(left: Type, right: Type, /) -> Type:
if order_ is Ordering.NONE:
raise TypeError(f"no ordering exists between '{left}' and '{right}'")
return left if order_ is Ordering.GREATER else right


class CastKind(enum.Enum):
"""A return value indicating the type of cast that can occur from one type to another."""

EQUAL = enum.auto()
"""The two types are equal; no cast node is required at all."""
IMPLICIT = enum.auto()
"""The 'from' type can be cast to the 'to' type implicitly. A :class:`~.expr.Cast` node with
``implicit==True`` is the minimum required to specify this."""
LOSSLESS = enum.auto()
"""The 'from' type can be cast to the 'to' type explicitly, and the cast will be lossless. This
requires a :class:`~.expr.Cast`` node with ``implicit=False``, but there's no danger from
inserting one."""
DANGEROUS = enum.auto()
"""The 'from' type has a defined cast to the 'to' type, but depending on the value, it may lose
data. A user would need to manually specify casts."""
NONE = enum.auto()
"""There is no casting permitted from the 'from' type to the 'to' type."""


def _uint_cast(from_: Uint, to_: Uint, /) -> CastKind:
if from_.width == to_.width:
return CastKind.EQUAL
if from_.width < to_.width:
return CastKind.LOSSLESS
return CastKind.DANGEROUS


_ALLOWED_CASTS = {
(Bool, Bool): lambda _a, _b, /: CastKind.EQUAL,
(Bool, Uint): lambda _a, _b, /: CastKind.LOSSLESS,
(Uint, Bool): lambda _a, _b, /: CastKind.IMPLICIT,
(Uint, Uint): _uint_cast,
}


def cast_kind(from_: Type, to_: Type, /) -> CastKind:
"""Determine the sort of cast that is required to move from the left type to the right type.
Examples:
.. code-block:: python
>>> from qiskit.circuit.classical import types
>>> types.cast_kind(types.Bool(), types.Bool())
<CastKind.EQUAL: 1>
>>> types.cast_kind(types.Uint(8), types.Bool())
<CastKind.IMPLICIT: 2>
>>> types.cast_kind(types.Bool(), types.Uint(8))
<CastKind.LOSSLESS: 3>
>>> types.cast_kind(types.Uint(16), types.Uint(8))
<CastKind.DANGEROUS: 4>
"""
if (coercer := _ALLOWED_CASTS.get((from_.kind, to_.kind))) is None:
return CastKind.NONE
return coercer(from_, to_)
Loading

0 comments on commit c619ef9

Please sign in to comment.