Skip to content

Test terms and values

A test term is a let expression the runner evaluates on the host; TermEvaluator runs a call to an entry point on the reference machine and builds a data value from a constructor application. The values a test computes with, and how they compare and print, are in quivers.testing.values.

terms

Evaluating test terms against a checked module.

A test term is a let expression evaluated on the host:

  • a numeric literal is exact: an integer literal is an int, a decimal literal the rational it spells (0.25 is 1/4);
  • +, - and * keep integers integral, and / is exact division, so 1/4 is the rational one quarter;
  • comparisons, &&, || and not are the host's;
  • a name is a let binding or a property's variable, and otherwise a constructor without fields;
  • a call f(...) runs f on the reference machine when f is a computation or program of the module, and builds a data value when f is a constructor. Arguments are positional or named; a named argument whose name is a static binder of the computation instantiates it.

Each argument is checked against the type it is passed at, which is how a nullary constructor of a parameterized family, or an integer passed as a real, gets its type. A run evaluates in the test's number domain: exactly, over the rationals, unless the test declares floating numbers.

Number

Number = Fraction | int | float

A number a test computes with.

FunctionBody

FunctionBody = Callable[[tuple[Value, ...]], tuple[Computation, TypeExpr, EffectRow]]

The body of a function a test term names, from the values of its parameters: the computation, its result type, and its effect row.

HeldResult didactic-model

HeldResult(*, value: HeldValue = field(opaque=True, extras=OPAQUE_BY_IDENTITY), type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A run's result as the machine holds it, with its type.

PARAMETER DESCRIPTION
value

The result.

TYPE: HeldValue DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

type

Its type at the run's static arguments.

TYPE: TypeExpr DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

TermError

TermError(message: str, line: int = 0, col: int = 0)

Bases: ValueError

A test term that cannot be evaluated, located at its source.

PARAMETER DESCRIPTION
message

What is wrong.

TYPE: str

line

The 1-based source line, or 0 when unknown.

TYPE: int DEFAULT: 0

col

The 0-based source column.

TYPE: int DEFAULT: 0

Source code in src/quivers/testing/terms.py
def __init__(self, message: str, line: int = 0, col: int = 0) -> None:
    location = f"line {line}, col {col}: " if line else ""
    super().__init__(location + message)
    self.line = line
    self.col = col

RunSettings didactic-model

RunSettings(*, numbers: NumberDomain, fuel: int, seed: int)

Bases: Model

How a test runs the module's entry points.

PARAMETER DESCRIPTION
numbers

The number domain of every run.

TYPE: NumberDomain

fuel

The step budget of each run.

TYPE: int

seed

The seed of the reference generator for each run of a program.

TYPE: int

TermEvaluator

TermEvaluator(module: QiecModule, settings: RunSettings)

Evaluate test terms against one checked module.

PARAMETER DESCRIPTION
module

The checked module whose entry points and constructors terms name.

TYPE: QiecModule

settings

The number domain, step budget and seed of each run.

TYPE: RunSettings

Source code in src/quivers/testing/terms.py
def __init__(self, module: QiecModule, settings: RunSettings) -> None:
    self.module = module
    self.settings = settings
    self.computations: dict[str, NamedComputation] = {
        computation.name: computation for computation in module.computations
    }
    self.programs: frozenset[str] = frozenset(
        point.name for point in entry_points(module) if point.kind == "program"
    )
    self.constructors: dict[str, ConstructorDecl] = {
        constructor.name: constructor for constructor in module.constructors
    }
    self.families: dict[FamilyId, FamilyDecl] = {
        family.id: family for family in module.families
    }

evaluate

evaluate(term: LetExprNode, scope: Mapping[str, TestValue], expected: TypeExpr | None = None) -> TestValue

Evaluate one term.

PARAMETER DESCRIPTION
term

The term.

TYPE: LetExprNode

scope

The values of the names bound so far.

TYPE: Mapping[str, TestValue]

expected

The type the value is passed at, when it is an argument.

TYPE: TypeExpr | None DEFAULT: None

RETURNS DESCRIPTION
TestValue

The value.

RAISES DESCRIPTION
TermError

If the term is not a test term, names nothing, or a run fails.

Source code in src/quivers/testing/terms.py
def evaluate(
    self,
    term: LetExprNode,
    scope: Mapping[str, TestValue],
    expected: TypeExpr | None = None,
) -> TestValue:
    """Evaluate one term.

    Parameters
    ----------
    term : LetExprNode
        The term.
    scope : Mapping[str, TestValue]
        The values of the names bound so far.
    expected : TypeExpr | None
        The type the value is passed at, when it is an argument.

    Returns
    -------
    TestValue
        The value.

    Raises
    ------
    TermError
        If the term is not a test term, names nothing, or a run fails.
    """
    if isinstance(term, LetExprLiteral):
        if term.integral:
            return int(term.value)
        return decimal_fraction(float(term.value))
    if isinstance(term, LetExprBool):
        return term.value
    if isinstance(term, LetExprString):
        return term.value
    if isinstance(term, LetExprUnit):
        return ()
    if isinstance(term, LetExprTuple | LetExprList):
        components = self._component_types(expected, len(term.items))
        return tuple(
            self.evaluate(item, scope, component)
            for item, component in zip(term.items, components, strict=True)
        )
    if isinstance(term, LetExprVar):
        if term.name in scope:
            return scope[term.name]
        if term.name in self.constructors:
            return self._construct(term.name, (), (), expected, scope, term)
        raise TermError(
            f"{term.name!r} names no binding or constructor", term.line, term.col
        )
    if isinstance(term, LetExprUnaryOp):
        operand = self.evaluate(term.operand, scope)
        if term.op == "not":
            if not isinstance(operand, bool):
                raise TermError(
                    "`not` applies to a truth value", term.line, term.col
                )
            return not operand
        if isinstance(operand, bool) or not isinstance(
            operand, Fraction | float | int
        ):
            raise TermError("`-` applies to a number", term.line, term.col)
        return -operand
    if isinstance(term, LetExprBinOp):
        return self._binary(term, scope)
    if isinstance(term, LetExprCall):
        return self._call(term, scope, expected)
    raise TermError(
        f"a {type(term).__name__.removeprefix('LetExpr').lower()} expression is "
        "not a test term; "
        "compute it in a computation of the module and run that",
        getattr(term, "line", 0),
        getattr(term, "col", 0),
    )

operands

operands(term: LetExprBinOp, scope: Mapping[str, TestValue]) -> tuple[TestValue, TestValue]

Evaluate the two operands of a binary operation.

The right operand is read at the type of the left one when the left is a data value, so reverse(xs) == Cons(2, Cons(1, Nil)) builds the expected list at the type the run returned.

PARAMETER DESCRIPTION
term

The operation.

TYPE: LetExprBinOp

scope

The bindings.

TYPE: Mapping[str, TestValue]

RETURNS DESCRIPTION
tuple[TestValue, TestValue]

The left and right values.

Source code in src/quivers/testing/terms.py
def operands(
    self, term: LetExprBinOp, scope: Mapping[str, TestValue]
) -> tuple[TestValue, TestValue]:
    """Evaluate the two operands of a binary operation.

    The right operand is read at the type of the left one when the left
    is a data value, so ``reverse(xs) == Cons(2, Cons(1, Nil))`` builds
    the expected list at the type the run returned.

    Parameters
    ----------
    term : LetExprBinOp
        The operation.
    scope : Mapping[str, TestValue]
        The bindings.

    Returns
    -------
    tuple[TestValue, TestValue]
        The left and right values.
    """
    left = self.evaluate(term.left, scope)
    expected = left.result_type if isinstance(left, RuntimeConstructor) else None
    return left, self.evaluate(term.right, scope, expected)

function

function(term: LetExprNode, expected: FunctionType, scope: Mapping[str, TestValue]) -> RuntimeClosure

A computation or constructor passed where a function is expected.

The name of a computation is a function value: applying it calls the computation with the argument, or with the argument's components when the computation takes several values. A computation with static arguments is used at the instance the expected function type fixes, as the elaborator reads a named computation used as a value. The name of a constructor stands for the function that applies it to its fields, at the family type the expected result fixes. A call of a computation that returns a function is run, and its result is the function.

PARAMETER DESCRIPTION
term

The argument: the name of a computation or a constructor, or a call that returns a function.

TYPE: LetExprNode

expected

The function type of the parameter it is passed to.

TYPE: FunctionType

scope

The bindings, for a call's arguments.

TYPE: Mapping[str, TestValue]

RETURNS DESCRIPTION
RuntimeClosure

The function, closed over nothing.

RAISES DESCRIPTION
TermError

If the term names neither a computation nor a constructor, or the expected type does not determine its static arguments or is not its type.

Source code in src/quivers/testing/terms.py
def function(
    self,
    term: LetExprNode,
    expected: FunctionType,
    scope: Mapping[str, TestValue],
) -> RuntimeClosure:
    """A computation or constructor passed where a function is expected.

    The name of a computation is a function value: applying it calls the
    computation with the argument, or with the argument's components
    when the computation takes several values. A computation with static
    arguments is used at the instance the expected function type fixes,
    as the elaborator reads a named computation used as a value. The
    name of a constructor stands for the function that applies it to its
    fields, at the family type the expected result fixes. A call of a
    computation that returns a function is run, and its result is the
    function.

    Parameters
    ----------
    term : LetExprNode
        The argument: the name of a computation or a constructor, or a
        call that returns a function.
    expected : FunctionType
        The function type of the parameter it is passed to.
    scope : Mapping[str, TestValue]
        The bindings, for a call's arguments.

    Returns
    -------
    RuntimeClosure
        The function, closed over nothing.

    Raises
    ------
    TermError
        If the term names neither a computation nor a constructor, or
        the expected type does not determine its static arguments or is
        not its type.
    """
    if (
        isinstance(term, LetExprCall)
        and term.func in self.computations
        and term.func not in self.programs
    ):
        return self._returned_function(term, expected, scope)
    if isinstance(term, LetExprVar) and term.name in self.computations:
        parameters, body = self._computation_function(term, expected)
    elif isinstance(term, LetExprVar) and term.name in self.constructors:
        parameters, body = self._constructor_function(term, expected)
    else:
        raise TermError(
            "a function argument names a computation or a constructor of the module",
            getattr(term, "line", 0),
            getattr(term, "col", 0),
        )
    argument = Local(name="__test_argument", type=function_domain(parameters))
    values: tuple[Value, ...] = (
        (Var(local=argument),)
        if len(parameters) == 1
        else tuple(
            Projection(
                value=Var(local=argument), position=position, result_type=type_
            )
            for position, type_ in enumerate(parameters)
        )
    )
    computation, result, effects = body(values)
    return RuntimeClosure(
        function=Lambda(
            code=ComputationId.derive(
                self.module.module, "test-function", term.name
            ),
            name=term.name,
            parameter=argument,
            body=computation,
            result_type=FunctionType(
                parameter=argument.type, result=result, effects=effects
            ),
            origin=self._origin(term),
        ),
        environment={},
    )

machine_argument

machine_argument(value: TestValue, type_: TypeExpr, term: LetExprNode | None) -> TestValue

A test value as a run of the test's domain takes it at a type.

PARAMETER DESCRIPTION
value

The value.

TYPE: TestValue

type_

The parameter's type.

TYPE: TypeExpr

term

The argument, for the diagnostic's location; None for a generated value.

TYPE: LetExprNode | None

RETURNS DESCRIPTION
TestValue

The value: an integer for an Int, a fraction for a real of an exact run, a float for a real of a floating one.

RAISES DESCRIPTION
TermError

If a rational that is not an integer is passed as an Int.

Source code in src/quivers/testing/terms.py
def machine_argument(
    self, value: TestValue, type_: TypeExpr, term: LetExprNode | None
) -> TestValue:
    """A test value as a run of the test's domain takes it at a type.

    Parameters
    ----------
    value : TestValue
        The value.
    type_ : TypeExpr
        The parameter's type.
    term : LetExprNode | None
        The argument, for the diagnostic's location; ``None`` for a
        generated value.

    Returns
    -------
    TestValue
        The value: an integer for an ``Int``, a fraction for a real of
        an exact run, a float for a real of a floating one.

    Raises
    ------
    TermError
        If a rational that is not an integer is passed as an ``Int``.
    """
    kind = number_kind(type_)
    if kind == "integer" and isinstance(value, Fraction):
        if value.denominator != 1:
            raise TermError(
                f"the rational {value} is passed as an Int",
                getattr(term, "line", 0),
                getattr(term, "col", 0),
            )
        return int(value)
    if kind == "real" and not self.settings.numbers.is_exact:
        return self._host_argument(value)
    return value

machine_field

machine_field(value: TestValue, type_: TypeExpr, term: LetExprNode | None) -> MachineValue

A field value as the machine holds it in a data value.

PARAMETER DESCRIPTION
value

The value.

TYPE: TestValue

type_

The field's type.

TYPE: TypeExpr

term

The field term, for diagnostics; None for a generated value.

TYPE: LetExprNode | None

RETURNS DESCRIPTION
MachineValue

The value converted by the field's type into the run's numbers.

Source code in src/quivers/testing/terms.py
def machine_field(
    self, value: TestValue, type_: TypeExpr, term: LetExprNode | None
) -> MachineValue:
    """A field value as the machine holds it in a data value.

    Parameters
    ----------
    value : TestValue
        The value.
    type_ : TypeExpr
        The field's type.
    term : LetExprNode | None
        The field term, for diagnostics; ``None`` for a generated value.

    Returns
    -------
    MachineValue
        The value converted by the field's type into the run's numbers.
    """
    converted = self.machine_argument(value, type_, term)
    return _machine_held(machine_value(type_, converted, self.settings.numbers))

family_type

family_type(family: FamilyDecl, expected: TypeExpr | None, line: int = 0, col: int = 0) -> TypeApplication

The type of a family's value, at the expected instance.

PARAMETER DESCRIPTION
family

The family.

TYPE: FamilyDecl

expected

The type the value is passed at.

TYPE: TypeExpr | None

line

The source line, for diagnostics.

TYPE: int DEFAULT: 0

col

The source column, for diagnostics.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
TypeApplication

expected when it is an instance of the family, the family's type when it has no parameters or indices.

RAISES DESCRIPTION
TermError

If the family has parameters or indices and no instance of it is expected, or another type is.

Source code in src/quivers/testing/terms.py
def family_type(
    self,
    family: FamilyDecl,
    expected: TypeExpr | None,
    line: int = 0,
    col: int = 0,
) -> TypeApplication:
    """The type of a family's value, at the expected instance.

    Parameters
    ----------
    family : FamilyDecl
        The family.
    expected : TypeExpr | None
        The type the value is passed at.
    line : int
        The source line, for diagnostics.
    col : int
        The source column, for diagnostics.

    Returns
    -------
    TypeApplication
        ``expected`` when it is an instance of the family, the family's
        type when it has no parameters or indices.

    Raises
    ------
    TermError
        If the family has parameters or indices and no instance of it
        is expected, or another type is.
    """
    constructor = family.type_constructor
    if (
        isinstance(expected, TypeApplication)
        and expected.constructor == constructor
    ):
        return expected
    if expected is not None and expected not in (BOOL, INT, STRING, UNIT):
        raise TermError(
            f"a value of {family.name!r} is passed where {render_static(expected)} is expected",
            line,
            col,
        )
    if constructor.telescope:
        raise TermError(
            f"a value of {family.name!r} needs the type it is passed at, since the "
            "family has static parameters; pass it as an argument or bind it "
            "with a property variable of that type",
            line,
            col,
        )
    return TypeApplication(constructor=constructor)

type_argument

type_argument(argument: StaticArgument) -> TypeExpr | None

A static argument that is a type, as a type.

PARAMETER DESCRIPTION
argument

A type, row, index, or effect.

TYPE: StaticArgument

RETURNS DESCRIPTION
TypeExpr | None

The argument when it is a type; None otherwise.

Source code in src/quivers/testing/terms.py
def type_argument(argument: StaticArgument) -> TypeExpr | None:
    """A static argument that is a type, as a type.

    Parameters
    ----------
    argument : StaticArgument
        A type, row, index, or effect.

    Returns
    -------
    TypeExpr | None
        The argument when it is a type; ``None`` otherwise.
    """
    if _is_type(argument):
        return argument
    return None

values_equal

values_equal(left: TestValue, right: TestValue) -> bool

Structural equality of two test values.

PARAMETER DESCRIPTION
left

One value.

TYPE: TestValue

right

The other.

TYPE: TestValue

RETURNS DESCRIPTION
bool

Numbers by exact value, tuples componentwise, data values by constructor and fields, anything else by ==.

Source code in src/quivers/testing/terms.py
def values_equal(left: TestValue, right: TestValue) -> bool:
    """Structural equality of two test values.

    Parameters
    ----------
    left : TestValue
        One value.
    right : TestValue
        The other.

    Returns
    -------
    bool
        Numbers by exact value, tuples componentwise, data values by
        constructor and fields, anything else by ``==``.
    """
    if isinstance(left, RuntimeConstructor) and isinstance(right, RuntimeConstructor):
        if left.constructor != right.constructor or len(left.fields) != len(
            right.fields
        ):
            return False
        return all(
            values_equal(read_value(_machine_held(a)), read_value(_machine_held(b)))
            for a, b in zip(left.fields, right.fields, strict=True)
        )
    if isinstance(left, tuple) and isinstance(right, tuple):
        return len(left) == len(right) and all(
            values_equal(a, b) for a, b in zip(left, right, strict=True)
        )
    if isinstance(left, bool) != isinstance(right, bool):
        return False
    return left == right

values

The values a test computes with, and how they compare and print.

A test runs on the host: its terms evaluate to host values, and a call to an entry point of the module runs it on the reference machine and reads its result back at the host boundary (quivers.qiec.numbers.host_value). An exact run returns its reals as fractions.Fraction; a floating run returns them as float. Integers are int, truth values bool, strings str, products and tensors tuples, the unit value the empty tuple, and a value of a data family the machine's RuntimeConstructor.

canonical reads a value into a form that compares structurally (a data value becomes its constructor's name and its fields), and render prints that form in QVR's surface spelling.

TestValue

TestValue = Fraction | int | float | bool | str | RuntimeConstructor | tuple['TestValue', ...]

A host value a test term evaluates to.

MachineValue

MachineValue = Tensor | Fraction | int | float | bool | str | RuntimeConstructor | tuple['MachineValue', ...]

A value as the machine holds it: a tensor for a number or tensor of numbers, a tuple of machine values, and the host form of every other value.

Canonical

Canonical = Fraction | int | float | bool | str | Constructed | tuple['Canonical', ...]

A test value in the form that compares structurally.

Constructed didactic-model

Constructed(*, constructor: str, fields: tuple[Canonical, ...] = field(opaque=True, default=(), extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A data value read structurally: a constructor and its fields.

PARAMETER DESCRIPTION
constructor

The constructor's source name.

TYPE: str

fields

The fields, canonical.

TYPE: tuple[Canonical, ...] DEFAULT: field(opaque=True, default=(), extras=OPAQUE_BY_VALUE)

UnreadableValue

Bases: TypeError

A machine value with no host form a test can compare.

read_value

read_value(value: MachineValue) -> TestValue

A machine result read as a test value.

PARAMETER DESCRIPTION
value

A value the machine returned, or a host value.

TYPE: MachineValue

RETURNS DESCRIPTION
TestValue

The value at the host boundary: an exact rational tensor as fractions, a floating tensor as floats, an integer or truth tensor as int or bool, nested tuples for a tensor of higher rank.

RAISES DESCRIPTION
UnreadableValue

If the value is neither a number, a tensor, a string, a tuple, nor a data value.

Source code in src/quivers/testing/values.py
def read_value(value: MachineValue) -> TestValue:
    """A machine result read as a test value.

    Parameters
    ----------
    value : MachineValue
        A value the machine returned, or a host value.

    Returns
    -------
    TestValue
        The value at the host boundary: an exact rational tensor as
        fractions, a floating tensor as floats, an integer or truth tensor
        as ``int`` or ``bool``, nested tuples for a tensor of higher rank.

    Raises
    ------
    UnreadableValue
        If the value is neither a number, a tensor, a string, a tuple, nor
        a data value.
    """
    if isinstance(value, RuntimeConstructor | bool | int | float | str | Fraction):
        return value
    if isinstance(value, torch.Tensor):
        return _host(host_value(value))
    return tuple(read_value(item) for item in value)

canonical

canonical(value: TestValue, constructors: Mapping[ConstructorId, str]) -> Canonical

A test value in the form that compares structurally.

PARAMETER DESCRIPTION
value

The value.

TYPE: TestValue

constructors

The source name of each constructor of the module.

TYPE: Mapping[ConstructorId, str]

RETURNS DESCRIPTION
Canonical

Data values as Constructed, fields read through read_value.

Source code in src/quivers/testing/values.py
def canonical(value: TestValue, constructors: Mapping[ConstructorId, str]) -> Canonical:
    """A test value in the form that compares structurally.

    Parameters
    ----------
    value : TestValue
        The value.
    constructors : Mapping[ConstructorId, str]
        The source name of each constructor of the module.

    Returns
    -------
    Canonical
        Data values as `Constructed`, fields read through `read_value`.
    """
    if isinstance(value, RuntimeConstructor):
        return Constructed(
            constructor=constructors.get(value.constructor, str(value.constructor)),
            fields=tuple(
                canonical(_field_value(item), constructors) for item in value.fields
            ),
        )
    if isinstance(value, tuple):
        return tuple(canonical(item, constructors) for item in value)
    return value

render

render(value: Canonical) -> str

Print a canonical value in QVR's surface spelling.

PARAMETER DESCRIPTION
value

The value.

TYPE: Canonical

RETURNS DESCRIPTION
str

true/false for truth values, p/q for a rational that is not an integer, the float's repr, a quoted string, (a, b) for a tuple, and C(a, b) for a data value.

Source code in src/quivers/testing/values.py
def render(value: Canonical) -> str:
    """Print a canonical value in QVR's surface spelling.

    Parameters
    ----------
    value : Canonical
        The value.

    Returns
    -------
    str
        ``true``/``false`` for truth values, ``p/q`` for a rational that is
        not an integer, the float's ``repr``, a quoted string, ``(a, b)``
        for a tuple, and ``C(a, b)`` for a data value.
    """
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, Fraction):
        if value.denominator == 1:
            return _render_integer(value.numerator)
        return str(value)
    if isinstance(value, int):
        return _render_integer(value)
    if isinstance(value, float):
        return repr(value)
    if isinstance(value, str):
        return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
    if isinstance(value, Constructed):
        if not value.fields:
            return value.constructor
        return (
            f"{value.constructor}({', '.join(render(item) for item in value.fields)})"
        )
    if len(value) == 0:
        return "unit"
    return "(" + ", ".join(render(item) for item in value) + ")"

to_json

to_json(value: Canonical) -> str | int | float | bool | list | dict[str, str | list]

A canonical value as JSON data for a machine-readable report.

PARAMETER DESCRIPTION
value

The value.

TYPE: Canonical

RETURNS DESCRIPTION
str | int | float | bool | list | dict

A rational as its p/q string (exact, so it is never rounded), an integer, float, truth value or string as itself, a tuple as a list, and a data value as {"constructor": ..., "fields": [...]}.

Source code in src/quivers/testing/values.py
def to_json(
    value: Canonical,
) -> str | int | float | bool | list | dict[str, str | list]:
    """A canonical value as JSON data for a machine-readable report.

    Parameters
    ----------
    value : Canonical
        The value.

    Returns
    -------
    str | int | float | bool | list | dict
        A rational as its ``p/q`` string (exact, so it is never rounded), an
        integer, float, truth value or string as itself, a tuple as a list,
        and a data value as ``{"constructor": ..., "fields": [...]}``.
    """
    if isinstance(value, bool | int | float | str):
        return value
    if isinstance(value, Fraction):
        return str(value)
    if isinstance(value, Constructed):
        return {
            "constructor": value.constructor,
            "fields": [to_json(item) for item in value.fields],
        }
    return [to_json(item) for item in value]