Skip to content

Generators and shrinking

Each checked type a property quantifies over has a Generator, built from the type's structure by generator_for: it enumerates a finite type, draws a value of a given size from an infinite one, and shrinks a failing value.

generators

Values a property quantifies over: enumeration, generation, shrinking.

A property's variable ranges over its type. generator_for gives each checked QIEC type a Generator, by the type's structure alone, so every declared data family has one without code written for it:

  • Bool and Unit, a product of finite types, a tensor of a finite element type at a literal shape, and a closed family without parameters that no constructor reaches again (no recursion) are finite: the generator enumerates every value, and the property is checked exhaustively;
  • Int, Real, String, and a recursive family are generated: the generator draws a value of a given size from a seeded random source (Claessen and Hughes 2000), and shrinks a failing value to smaller ones.

A recursive family is generated by size: a constructor whose fields reach the family again is chosen only while size remains, and each such field gets a share of it, so generation terminates. A value shrinks to its subterms of its own type first, then field by field.

A family whose module declares a computation F__arbitrary(size : Int) : F generates its values by running it (the shape a derived Arbitrary instance has); structural shrinking still applies.

GenerationError

Bases: ValueError

A type has no generator, with the declared property that rules it out.

Generator

Bases: Protocol

How a property's variable ranges over its type.

finite

finite() -> int | None

The number of values, when the type is finite.

RETURNS DESCRIPTION
int | None

The count, or None for a type with unboundedly many values.

Source code in src/quivers/testing/generators.py
def finite(self) -> int | None:
    """The number of values, when the type is finite.

    Returns
    -------
    int | None
        The count, or ``None`` for a type with unboundedly many values.
    """
    ...

enumerate

enumerate() -> Iterator[TestValue]

Every value of a finite type, smallest first.

RETURNS DESCRIPTION
Iterator[TestValue]

The values.

Source code in src/quivers/testing/generators.py
def enumerate(self) -> Iterator[TestValue]:
    """Every value of a finite type, smallest first.

    Returns
    -------
    Iterator[TestValue]
        The values.
    """
    ...

sample

sample(source: Random, size: int) -> TestValue

Draw one value of at most a given size.

PARAMETER DESCRIPTION
source

The seeded random source.

TYPE: Random

size

The size bound.

TYPE: int

RETURNS DESCRIPTION
TestValue

The value.

Source code in src/quivers/testing/generators.py
def sample(self, source: random.Random, size: int) -> TestValue:
    """Draw one value of at most a given size.

    Parameters
    ----------
    source : random.Random
        The seeded random source.
    size : int
        The size bound.

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

shrink

shrink(value: TestValue) -> Iterator[TestValue]

Values smaller than value, most aggressive first.

PARAMETER DESCRIPTION
value

A value this generator produced.

TYPE: TestValue

RETURNS DESCRIPTION
Iterator[TestValue]

Candidates, each strictly smaller.

Source code in src/quivers/testing/generators.py
def shrink(self, value: TestValue) -> Iterator[TestValue]:
    """Values smaller than ``value``, most aggressive first.

    Parameters
    ----------
    value : TestValue
        A value this generator produced.

    Returns
    -------
    Iterator[TestValue]
        Candidates, each strictly smaller.
    """
    ...

BoolGenerator

The two truth values; true shrinks to false.

finite

finite() -> int | None

Two values.

RETURNS DESCRIPTION
int | None

2.

Source code in src/quivers/testing/generators.py
def finite(self) -> int | None:
    """Two values.

    Returns
    -------
    int | None
        ``2``.
    """
    return 2

enumerate

enumerate() -> Iterator[TestValue]

false then true.

RETURNS DESCRIPTION
Iterator[TestValue]

The values.

Source code in src/quivers/testing/generators.py
def enumerate(self) -> Iterator[TestValue]:
    """``false`` then ``true``.

    Returns
    -------
    Iterator[TestValue]
        The values.
    """
    yield False
    yield True

sample

sample(source: Random, size: int) -> TestValue

A fair coin.

PARAMETER DESCRIPTION
source

The random source.

TYPE: Random

size

Unused.

TYPE: int

RETURNS DESCRIPTION
TestValue

A truth value.

Source code in src/quivers/testing/generators.py
def sample(self, source: random.Random, size: int) -> TestValue:
    """A fair coin.

    Parameters
    ----------
    source : random.Random
        The random source.
    size : int
        Unused.

    Returns
    -------
    TestValue
        A truth value.
    """
    return source.random() < 0.5

shrink

shrink(value: TestValue) -> Iterator[TestValue]

false for true.

PARAMETER DESCRIPTION
value

The value.

TYPE: TestValue

RETURNS DESCRIPTION
Iterator[TestValue]

The candidates.

Source code in src/quivers/testing/generators.py
def shrink(self, value: TestValue) -> Iterator[TestValue]:
    """``false`` for ``true``.

    Parameters
    ----------
    value : TestValue
        The value.

    Returns
    -------
    Iterator[TestValue]
        The candidates.
    """
    if value is True:
        yield False

UnitGenerator

The one unit value.

finite

finite() -> int | None

One value.

RETURNS DESCRIPTION
int | None

1.

Source code in src/quivers/testing/generators.py
def finite(self) -> int | None:
    """One value.

    Returns
    -------
    int | None
        ``1``.
    """
    return 1

enumerate

enumerate() -> Iterator[TestValue]

The unit value.

RETURNS DESCRIPTION
Iterator[TestValue]

The value.

Source code in src/quivers/testing/generators.py
def enumerate(self) -> Iterator[TestValue]:
    """The unit value.

    Returns
    -------
    Iterator[TestValue]
        The value.
    """
    yield ()

sample

sample(source: Random, size: int) -> TestValue

The unit value.

PARAMETER DESCRIPTION
source

Unused.

TYPE: Random

size

Unused.

TYPE: int

RETURNS DESCRIPTION
TestValue

The empty tuple.

Source code in src/quivers/testing/generators.py
def sample(self, source: random.Random, size: int) -> TestValue:
    """The unit value.

    Parameters
    ----------
    source : random.Random
        Unused.
    size : int
        Unused.

    Returns
    -------
    TestValue
        The empty tuple.
    """
    return ()

shrink

shrink(value: TestValue) -> Iterator[TestValue]

No candidates.

PARAMETER DESCRIPTION
value

The value.

TYPE: TestValue

RETURNS DESCRIPTION
Iterator[TestValue]

Nothing.

Source code in src/quivers/testing/generators.py
def shrink(self, value: TestValue) -> Iterator[TestValue]:
    """No candidates.

    Parameters
    ----------
    value : TestValue
        The value.

    Returns
    -------
    Iterator[TestValue]
        Nothing.
    """
    return iter(())

IntGenerator

Integers between -size and size, shrinking toward zero.

finite

finite() -> int | None

Unboundedly many values.

RETURNS DESCRIPTION
int | None

None.

Source code in src/quivers/testing/generators.py
def finite(self) -> int | None:
    """Unboundedly many values.

    Returns
    -------
    int | None
        ``None``.
    """
    return None

enumerate

enumerate() -> Iterator[TestValue]

No enumeration; the type is infinite.

RETURNS DESCRIPTION
Iterator[TestValue]

Never returns.

RAISES DESCRIPTION
GenerationError

Always.

Source code in src/quivers/testing/generators.py
def enumerate(self) -> Iterator[TestValue]:
    """No enumeration; the type is infinite.

    Returns
    -------
    Iterator[TestValue]
        Never returns.

    Raises
    ------
    GenerationError
        Always.
    """
    raise GenerationError("Int has unboundedly many values")

sample

sample(source: Random, size: int) -> TestValue

A uniform integer in [-size, size].

PARAMETER DESCRIPTION
source

The random source.

TYPE: Random

size

The bound.

TYPE: int

RETURNS DESCRIPTION
TestValue

The integer.

Source code in src/quivers/testing/generators.py
def sample(self, source: random.Random, size: int) -> TestValue:
    """A uniform integer in ``[-size, size]``.

    Parameters
    ----------
    source : random.Random
        The random source.
    size : int
        The bound.

    Returns
    -------
    TestValue
        The integer.
    """
    return source.randint(-size, size)

shrink

shrink(value: TestValue) -> Iterator[TestValue]

0, the absolute value, then halves toward zero.

PARAMETER DESCRIPTION
value

An integer.

TYPE: TestValue

RETURNS DESCRIPTION
Iterator[TestValue]

The candidates, each closer to zero.

Source code in src/quivers/testing/generators.py
def shrink(self, value: TestValue) -> Iterator[TestValue]:
    """``0``, the absolute value, then halves toward zero.

    Parameters
    ----------
    value : TestValue
        An integer.

    Returns
    -------
    Iterator[TestValue]
        The candidates, each closer to zero.
    """
    if not isinstance(value, int) or isinstance(value, bool) or value == 0:
        return
    yield 0
    if value < 0:
        yield -value
    step = value // 2 if value > 0 else -((-value) // 2)
    while step != 0:
        yield value - step
        step = step // 2 if step > 0 else -((-step) // 2)

RealGenerator

Rationals p/q with |p| <= size**2 and 1 <= q <= size.

A real a property draws is an exact rational, so an exact run checks the property at exactly that point; a floating run takes the nearest float. It shrinks toward zero, to integers, then to simpler fractions.

finite

finite() -> int | None

Unboundedly many values.

RETURNS DESCRIPTION
int | None

None.

Source code in src/quivers/testing/generators.py
def finite(self) -> int | None:
    """Unboundedly many values.

    Returns
    -------
    int | None
        ``None``.
    """
    return None

enumerate

enumerate() -> Iterator[TestValue]

No enumeration; the type is infinite.

RETURNS DESCRIPTION
Iterator[TestValue]

Never returns.

RAISES DESCRIPTION
GenerationError

Always.

Source code in src/quivers/testing/generators.py
def enumerate(self) -> Iterator[TestValue]:
    """No enumeration; the type is infinite.

    Returns
    -------
    Iterator[TestValue]
        Never returns.

    Raises
    ------
    GenerationError
        Always.
    """
    raise GenerationError("Real has unboundedly many values")

sample

sample(source: Random, size: int) -> TestValue

A rational of the given size.

PARAMETER DESCRIPTION
source

The random source.

TYPE: Random

size

The bound.

TYPE: int

RETURNS DESCRIPTION
TestValue

The rational.

Source code in src/quivers/testing/generators.py
def sample(self, source: random.Random, size: int) -> TestValue:
    """A rational of the given size.

    Parameters
    ----------
    source : random.Random
        The random source.
    size : int
        The bound.

    Returns
    -------
    TestValue
        The rational.
    """
    bound = max(size, 1)
    return Fraction(
        source.randint(-bound * bound, bound * bound), source.randint(1, bound)
    )

shrink

shrink(value: TestValue) -> Iterator[TestValue]

Simpler rationals: smaller denominators, then smaller numerators.

Every candidate p'/q' of p/q is smaller in the well-founded order of (q, |p|, p < 0): 0, the absolute value of a negative, the integer part and the nearest fractions of smaller denominator, then numerators moved toward zero over the same denominator.

PARAMETER DESCRIPTION
value

A rational.

TYPE: TestValue

RETURNS DESCRIPTION
Iterator[TestValue]

The candidates, each smaller.

Source code in src/quivers/testing/generators.py
def shrink(self, value: TestValue) -> Iterator[TestValue]:
    """Simpler rationals: smaller denominators, then smaller numerators.

    Every candidate ``p'/q'`` of ``p/q`` is smaller in the well-founded
    order of ``(q, |p|, p < 0)``: ``0``, the absolute value of a
    negative, the integer part and the nearest fractions of smaller
    denominator, then numerators moved toward zero over the same
    denominator.

    Parameters
    ----------
    value : TestValue
        A rational.

    Returns
    -------
    Iterator[TestValue]
        The candidates, each smaller.
    """
    if not isinstance(value, Fraction) or value == 0:
        return
    yield Fraction(0)
    if value < 0:
        yield -value
    if value.denominator > 1:
        yield Fraction(math.trunc(value))
        denominator = value.denominator // 2
        while denominator > 1:
            simpler = value.limit_denominator(denominator)
            if simpler.denominator < value.denominator:
                yield simpler
            denominator //= 2
    for numerator in IntGenerator().shrink(value.numerator):
        if isinstance(numerator, int) and numerator != 0:
            yield Fraction(numerator, value.denominator)

StringGenerator

Lowercase strings of length at most size, shrinking by deletion.

finite

finite() -> int | None

Unboundedly many values.

RETURNS DESCRIPTION
int | None

None.

Source code in src/quivers/testing/generators.py
def finite(self) -> int | None:
    """Unboundedly many values.

    Returns
    -------
    int | None
        ``None``.
    """
    return None

enumerate

enumerate() -> Iterator[TestValue]

No enumeration; the type is infinite.

RETURNS DESCRIPTION
Iterator[TestValue]

Never returns.

RAISES DESCRIPTION
GenerationError

Always.

Source code in src/quivers/testing/generators.py
def enumerate(self) -> Iterator[TestValue]:
    """No enumeration; the type is infinite.

    Returns
    -------
    Iterator[TestValue]
        Never returns.

    Raises
    ------
    GenerationError
        Always.
    """
    raise GenerationError("String has unboundedly many values")

sample

sample(source: Random, size: int) -> TestValue

A string of letters.

PARAMETER DESCRIPTION
source

The random source.

TYPE: Random

size

The length bound.

TYPE: int

RETURNS DESCRIPTION
TestValue

The string.

Source code in src/quivers/testing/generators.py
def sample(self, source: random.Random, size: int) -> TestValue:
    """A string of letters.

    Parameters
    ----------
    source : random.Random
        The random source.
    size : int
        The length bound.

    Returns
    -------
    TestValue
        The string.
    """
    length = source.randint(0, max(size, 0))
    return "".join(source.choice(self._LETTERS) for _ in range(length))

shrink

shrink(value: TestValue) -> Iterator[TestValue]

The empty string, halves, then each one-character deletion.

PARAMETER DESCRIPTION
value

A string.

TYPE: TestValue

RETURNS DESCRIPTION
Iterator[TestValue]

The candidates, each shorter.

Source code in src/quivers/testing/generators.py
def shrink(self, value: TestValue) -> Iterator[TestValue]:
    """The empty string, halves, then each one-character deletion.

    Parameters
    ----------
    value : TestValue
        A string.

    Returns
    -------
    Iterator[TestValue]
        The candidates, each shorter.
    """
    if not isinstance(value, str) or not value:
        return
    yield ""
    if len(value) > 1:
        yield value[: len(value) // 2]
        yield value[len(value) // 2 :]
    for position in range(len(value)):
        yield value[:position] + value[position + 1 :]

ProductGenerator

ProductGenerator(components: Sequence[Generator])

Tuples of component values; also a tensor at a literal shape.

PARAMETER DESCRIPTION
components

One generator per component.

TYPE: Sequence[Generator]

Source code in src/quivers/testing/generators.py
def __init__(self, components: Sequence[Generator]) -> None:
    self.components = tuple(components)

finite

finite() -> int | None

The product of the components' counts, when all are finite.

RETURNS DESCRIPTION
int | None

The count.

Source code in src/quivers/testing/generators.py
def finite(self) -> int | None:
    """The product of the components' counts, when all are finite.

    Returns
    -------
    int | None
        The count.
    """
    total = 1
    for component in self.components:
        count = component.finite()
        if count is None:
            return None
        total *= count
    return total

enumerate

enumerate() -> Iterator[TestValue]

Every tuple, in lexicographic order of the components'.

RETURNS DESCRIPTION
Iterator[TestValue]

The tuples.

Source code in src/quivers/testing/generators.py
def enumerate(self) -> Iterator[TestValue]:
    """Every tuple, in lexicographic order of the components'.

    Returns
    -------
    Iterator[TestValue]
        The tuples.
    """
    for values in product(
        *(component.enumerate() for component in self.components)
    ):
        yield tuple(values)

sample

sample(source: Random, size: int) -> TestValue

One value per component.

PARAMETER DESCRIPTION
source

The random source.

TYPE: Random

size

The size bound of each component.

TYPE: int

RETURNS DESCRIPTION
TestValue

The tuple.

Source code in src/quivers/testing/generators.py
def sample(self, source: random.Random, size: int) -> TestValue:
    """One value per component.

    Parameters
    ----------
    source : random.Random
        The random source.
    size : int
        The size bound of each component.

    Returns
    -------
    TestValue
        The tuple.
    """
    return tuple(component.sample(source, size) for component in self.components)

shrink

shrink(value: TestValue) -> Iterator[TestValue]

Shrink one component at a time.

PARAMETER DESCRIPTION
value

A tuple.

TYPE: TestValue

RETURNS DESCRIPTION
Iterator[TestValue]

The candidates.

Source code in src/quivers/testing/generators.py
def shrink(self, value: TestValue) -> Iterator[TestValue]:
    """Shrink one component at a time.

    Parameters
    ----------
    value : TestValue
        A tuple.

    Returns
    -------
    Iterator[TestValue]
        The candidates.
    """
    if not isinstance(value, tuple) or len(value) != len(self.components):
        return
    for position, component in enumerate(self.components):
        for smaller in component.shrink(value[position]):
            yield value[:position] + (smaller,) + value[position + 1 :]

FamilyGenerator

FamilyGenerator(family: FamilyDecl, type_: TypeApplication, evaluator: TermEvaluator, arbitrary: NamedComputation | None = None, building: tuple[TypeExpr, ...] = ())

Values of a closed data family, by its constructors' fields.

PARAMETER DESCRIPTION
family

The family.

TYPE: FamilyDecl

type_

The instance of it the values have.

TYPE: TypeApplication

evaluator

The module and the run settings, which turn field values into the run's numbers.

TYPE: TermEvaluator

arbitrary

The module's F__arbitrary(size : Int) : F computation, which draws values in place of the structural generator when present.

TYPE: NamedComputation | None DEFAULT: None

building

The family instances whose generators enclose this one, so a family reached again through another is refused rather than recursed into without bound.

TYPE: tuple[TypeExpr, ...] DEFAULT: ()

Source code in src/quivers/testing/generators.py
def __init__(
    self,
    family: FamilyDecl,
    type_: TypeApplication,
    evaluator: TermEvaluator,
    arbitrary: NamedComputation | None = None,
    building: tuple[TypeExpr, ...] = (),
) -> None:
    if not family.closed:
        raise GenerationError(
            f"family {family.name!r} is opaque, so its values are not known "
            f"from its constructors; declare {family.name}__arbitrary"
        )
    if family.indices:
        raise GenerationError(
            f"family {family.name!r} is indexed, so which constructors build a "
            f"value depends on its indices; declare {family.name}__arbitrary"
        )
    self.family = family
    self.type_ = type_
    self.evaluator = evaluator
    self.arbitrary = arbitrary
    self.building = (*building, type_)
    by_id = {
        constructor.id: constructor for constructor in evaluator.module.constructors
    }
    self.constructors: tuple[ConstructorDecl, ...] = tuple(
        by_id[identity] for identity in family.constructors
    )
    substitution = instantiate_telescope(
        family.type_constructor.telescope, type_.arguments
    )
    self.field_types: dict[str, tuple[TypeExpr, ...]] = {}
    for constructor in self.constructors:
        if constructor.telescope:
            raise GenerationError(
                f"constructor {constructor.name!r} has static binders of its own "
                f"(an existential), which no generator can choose; declare "
                f"{family.name}__arbitrary"
            )
        self.field_types[constructor.name] = tuple(
            substitute_type(field.type, substitution)
            for field in constructor.fields
        )
    self._fields: dict[str, tuple[Generator | None, ...]] = {}

finite

finite() -> int | None

The number of values, when no constructor recurses.

RETURNS DESCRIPTION
int | None

The sum over constructors of the product of their fields' counts, or None when a field recurses or is infinite.

Source code in src/quivers/testing/generators.py
def finite(self) -> int | None:
    """The number of values, when no constructor recurses.

    Returns
    -------
    int | None
        The sum over constructors of the product of their fields'
        counts, or ``None`` when a field recurses or is infinite.
    """
    total = 0
    for constructor in self.constructors:
        count = 1
        for generator in self._field_generators(constructor):
            if generator is None:
                return None
            field_count = generator.finite()
            if field_count is None:
                return None
            count *= field_count
        total += count
    return total

enumerate

enumerate() -> Iterator[TestValue]

Every value, constructor by constructor.

RETURNS DESCRIPTION
Iterator[TestValue]

The values.

Source code in src/quivers/testing/generators.py
def enumerate(self) -> Iterator[TestValue]:
    """Every value, constructor by constructor.

    Returns
    -------
    Iterator[TestValue]
        The values.
    """
    for constructor in self.constructors:
        generators = [
            generator
            for generator in self._field_generators(constructor)
            if generator is not None
        ]
        for fields in product(*(generator.enumerate() for generator in generators)):
            yield self._build(constructor, tuple(fields))

sample

sample(source: Random, size: int) -> TestValue

Draw a value of at most size constructors deep.

PARAMETER DESCRIPTION
source

The random source.

TYPE: Random

size

The size bound.

TYPE: int

RETURNS DESCRIPTION
TestValue

The value.

RAISES DESCRIPTION
GenerationError

If every constructor recurses, so no value is finite.

Source code in src/quivers/testing/generators.py
def sample(self, source: random.Random, size: int) -> TestValue:
    """Draw a value of at most ``size`` constructors deep.

    Parameters
    ----------
    source : random.Random
        The random source.
    size : int
        The size bound.

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

    Raises
    ------
    GenerationError
        If every constructor recurses, so no value is finite.
    """
    if self.arbitrary is not None:
        return self._derived(source, size)
    leaves = [
        constructor
        for constructor in self.constructors
        if all(
            generator is not None
            for generator in self._field_generators(constructor)
        )
    ]
    if not leaves:
        raise GenerationError(
            f"every constructor of {self.family.name!r} contains the family again, "
            "so it has no finite value"
        )
    choices = list(self.constructors) if size > 0 else leaves
    constructor = source.choice(choices)
    generators = self._field_generators(constructor)
    recursive = sum(1 for generator in generators if generator is None)
    share = (size - 1) // recursive if recursive else size
    fields = tuple(
        self.sample(source, share)
        if generator is None
        else generator.sample(source, size)
        for generator in generators
    )
    return self._build(constructor, fields)

shrink

shrink(value: TestValue) -> Iterator[TestValue]

Subterms of the same type, then each field shrunk.

PARAMETER DESCRIPTION
value

A data value of the family.

TYPE: TestValue

RETURNS DESCRIPTION
Iterator[TestValue]

The candidates.

Source code in src/quivers/testing/generators.py
def shrink(self, value: TestValue) -> Iterator[TestValue]:
    """Subterms of the same type, then each field shrunk.

    Parameters
    ----------
    value : TestValue
        A data value of the family.

    Returns
    -------
    Iterator[TestValue]
        The candidates.
    """
    if not isinstance(value, RuntimeConstructor):
        return
    constructor = next(
        (item for item in self.constructors if item.id == value.constructor), None
    )
    if constructor is None:
        return
    generators = self._field_generators(constructor)
    for field, generator in zip(value.fields, generators, strict=True):
        if generator is None and isinstance(field, RuntimeConstructor):
            yield field
    for position, (field, generator) in enumerate(
        zip(value.fields, generators, strict=True)
    ):
        current = (
            field
            if isinstance(field, RuntimeConstructor)
            else read_value(_machine_held(field))
        )
        candidates = (
            self.shrink(current) if generator is None else generator.shrink(current)
        )
        for smaller in candidates:
            fields = [
                item
                if isinstance(item, RuntimeConstructor)
                else read_value(_machine_held(item))
                for item in value.fields
            ]
            fields[position] = smaller
            yield self._build(constructor, tuple(fields))

ListedGenerator

ListedGenerator(values: Sequence[TestValue])

A variable ranging over listed values, in the listed order.

PARAMETER DESCRIPTION
values

The values.

TYPE: Sequence[TestValue]

Source code in src/quivers/testing/generators.py
def __init__(self, values: Sequence[TestValue]) -> None:
    self.values = tuple(values)

finite

finite() -> int | None

The number of listed values.

RETURNS DESCRIPTION
int | None

The count.

Source code in src/quivers/testing/generators.py
def finite(self) -> int | None:
    """The number of listed values.

    Returns
    -------
    int | None
        The count.
    """
    return len(self.values)

enumerate

enumerate() -> Iterator[TestValue]

The listed values.

RETURNS DESCRIPTION
Iterator[TestValue]

The values.

Source code in src/quivers/testing/generators.py
def enumerate(self) -> Iterator[TestValue]:
    """The listed values.

    Returns
    -------
    Iterator[TestValue]
        The values.
    """
    return iter(self.values)

sample

sample(source: Random, size: int) -> TestValue

A listed value, uniformly.

PARAMETER DESCRIPTION
source

The random source.

TYPE: Random

size

Unused.

TYPE: int

RETURNS DESCRIPTION
TestValue

The value.

Source code in src/quivers/testing/generators.py
def sample(self, source: random.Random, size: int) -> TestValue:
    """A listed value, uniformly.

    Parameters
    ----------
    source : random.Random
        The random source.
    size : int
        Unused.

    Returns
    -------
    TestValue
        The value.
    """
    return source.choice(self.values)

shrink

shrink(value: TestValue) -> Iterator[TestValue]

The values listed before value.

PARAMETER DESCRIPTION
value

A listed value.

TYPE: TestValue

RETURNS DESCRIPTION
Iterator[TestValue]

The earlier values, first first.

Source code in src/quivers/testing/generators.py
def shrink(self, value: TestValue) -> Iterator[TestValue]:
    """The values listed before ``value``.

    Parameters
    ----------
    value : TestValue
        A listed value.

    Returns
    -------
    Iterator[TestValue]
        The earlier values, first first.
    """
    for item in self.values:
        if values_equal(item, value):
            return
        yield item

generator_for

generator_for(type_: TypeExpr, evaluator: TermEvaluator, building: tuple[TypeExpr, ...] = ()) -> Generator

The generator of a closed type's values.

PARAMETER DESCRIPTION
type_

The type.

TYPE: TypeExpr

evaluator

The module the type's families are declared in, and the run's settings.

TYPE: TermEvaluator

building

The family instances whose generators enclose this one.

TYPE: tuple[TypeExpr, ...] DEFAULT: ()

RETURNS DESCRIPTION
Generator

The generator.

RAISES DESCRIPTION
GenerationError

If the type has none: a function type, an opaque or indexed family, a family reached again through another family (mutual recursion), or a tensor of unknown shape.

Source code in src/quivers/testing/generators.py
def generator_for(
    type_: TypeExpr,
    evaluator: TermEvaluator,
    building: tuple[TypeExpr, ...] = (),
) -> Generator:
    """The generator of a closed type's values.

    Parameters
    ----------
    type_ : TypeExpr
        The type.
    evaluator : TermEvaluator
        The module the type's families are declared in, and the run's
        settings.
    building : tuple[TypeExpr, ...]
        The family instances whose generators enclose this one.

    Returns
    -------
    Generator
        The generator.

    Raises
    ------
    GenerationError
        If the type has none: a function type, an opaque or indexed family,
        a family reached again through another family (mutual recursion),
        or a tensor of unknown shape.
    """
    if type_ == BOOL:
        return BoolGenerator()
    if type_ == UNIT:
        return UnitGenerator()
    if type_ == INT:
        return IntGenerator()
    if type_ in (REAL, LOG_WEIGHT):
        return RealGenerator()
    if type_ == STRING:
        return StringGenerator()
    shape = tensor_shape(type_)
    if shape is not None:
        dimensions = static_shape(type_)
        if dimensions is None:
            raise GenerationError("a tensor variable needs a literal shape")
        element = generator_for(shape[0], evaluator, building)
        count = math.prod(dimensions)
        flat = ProductGenerator([element] * count)
        return _Reshaped(flat, dimensions)
    if isinstance(type_, TypeApplication):
        if type_.constructor.name.startswith("Product"):
            components: list[Generator] = []
            for argument in type_.arguments:
                component = type_argument(argument)
                if component is None:
                    raise GenerationError("a product's components are types")
                components.append(generator_for(component, evaluator, building))
            return ProductGenerator(components)
        family = next(
            (
                item
                for item in evaluator.module.families
                if item.type_constructor == type_.constructor
            ),
            None,
        )
        if family is not None:
            if type_ in building:
                raise GenerationError(
                    f"family {family.name!r} is reached again through another family; "
                    f"declare {family.name}__arbitrary"
                )
            return FamilyGenerator(
                family,
                type_,
                evaluator,
                _arbitrary(evaluator, family, type_),
                building,
            )
    raise GenerationError(f"no values are generated for the type {type_!r}")