Skip to content

Judgments

A JudgmentSystem runs moded judgments over the terms of a signature: it checks modes, searches for derivations with pattern matching and unification, infers outputs, and builds a goal's derivation chart under any semiring (Judgments). Program.judgments maps each declared judgment to its system.

judgments

Moded judgments over binding signatures: checkers, inference, and charts.

A judgment declares a relation between terms, such as a typing relation Ty(ctx, t, A), with a mode for each argument: in arguments are given and out arguments are computed. Its rules use the deduction rule form over second-order terms [@sewell2010ott; @pientka2010beluga]:

rule lam : Ty((ctx, x : A), M[x], B) |- Ty(ctx, Lam(x. M[x]), Arr(A, B))

A JudgmentSystem gives a judgment three readings.

  • Mode check. Read the premises left to right after the conclusion's inputs: a variable is determined once a conclusion input or any premise mentions it, and every variable of a conclusion output must be determined [@dunfield2021bidirectional]. A variable declared in the rule's bracket telescope, such as the a of a polymorphic constant's scheme, is fresh at every use. check_modes refuses a rule that fails, naming the variable.
  • Checker and inferencer. A well-moded judgment runs as a syntax-directed search. Inputs are matched against the rules' conclusions by second-order pattern matching (the scoped term argument) and first-order unification (the other arguments); variables that no input determines become unification variables, solved by constraint-based elaboration [@pottier2014hindley] with higher-order pattern unification where a binder is involved [@miller1991logic; @abel2011higher]. JudgmentSystem.solve yields every derivation of a goal.
  • Chart. A judgment is a deduction: its least fixed point in the Boolean semiring is derivability. JudgmentSystem.chart hands the derivation hypergraph of a goal to the agenda engine of quivers.stochastic.agenda under any chart semiring, so the log-probability semiring gives a distribution over typings and the Boolean semiring gives derivability.

A judgment has at most one argument of the context sort Context[T], a list of T values. The argument whose sort the signature binds variables of is scoped by it: its free variable i has the i-th entry, counted from the innermost, as its T. (ctx, x : A) extends a context, and the built-in judgment lookup(ctx, i, A) (modes in, in, out) reads an entry. A variable of the scoped sort S is matched by the pattern S.var(i).

A variable at a data position, such as the n of rule constant : |- Ty(ctx, Const(n, A), A), stands for the data value there (a data metavariable of quivers.structural.patterns): matching the scoped term binds it, unification compares it with another data value by equality, and a rule passes it through to its premises and outputs.

LOOKUP module-attribute

LOOKUP = 'lookup'

The built-in judgment that reads a context entry.

VARIABLE module-attribute

VARIABLE = 'var'

The member name of a scoped sort's variable pattern, as in Term.var(i).

AtomArgument

An argument of a judgment instance in a rule.

GoalArgument

GoalArgument = ContextValue | Term | Pattern | DataLeaf

A goal argument: a context, a scoped term, a closed pattern, or a data value.

JudgmentError

Bases: ValueError

A judgment declaration is ill-formed or ill-moded.

JudgmentFailure

Bases: JudgmentError

A goal has no derivation; the message names the failing constraint.

JudgmentArgument didactic-model

JudgmentArgument(*, name: str, sort: str, mode: Literal['in', 'out'], context: bool = False)

Bases: Model

One argument of a judgment form.

PARAMETER DESCRIPTION
name

Its name.

TYPE: str

sort

Its sort, or the entry sort of a context.

TYPE: str

mode

"in" or "out".

TYPE: str

context

Whether it is a context Context[sort].

TYPE: bool DEFAULT: False

JudgmentForm didactic-model

JudgmentForm(*, name: str, arguments: tuple[JudgmentArgument, ...] = ())

Bases: Model

A judgment's name and moded arguments.

PARAMETER DESCRIPTION
name

The judgment.

TYPE: str

arguments

Its arguments.

TYPE: tuple of JudgmentArgument DEFAULT: ()

ContextPattern didactic-model

ContextPattern(*, base: str, names: tuple[str, ...] = (), types: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A context in a rule: a context variable, possibly extended.

PARAMETER DESCRIPTION
base

The context variable.

TYPE: str

names

The names of the added entries, outermost first.

TYPE: tuple of str DEFAULT: ()

types

Their values.

TYPE: tuple of Pattern DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

VariablePattern didactic-model

VariablePattern(*, sort: str, index: str)

Bases: Model

S.var(i): a variable of the scoped sort, its index named i.

PARAMETER DESCRIPTION
sort

The scoped sort.

TYPE: str

index

The name its index is bound to.

TYPE: str

Atom didactic-model

Atom(*, judgment: str, arguments: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A judgment applied to patterns: a premise or conclusion.

PARAMETER DESCRIPTION
judgment

The judgment.

TYPE: str

arguments

Its arguments, in the form's order.

TYPE: tuple of AtomArgument DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

JudgmentRule didactic-model

JudgmentRule(*, name: str, premises: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), conclusion: Atom = field(opaque=True, extras=OPAQUE_BY_VALUE), schematic: tuple[str, ...] = (), weight: float = 0.0, line: int = 0, col: int = 0)

Bases: ValueModel

An inference rule of a judgment.

PARAMETER DESCRIPTION
name

Its name.

TYPE: str

premises

Its premises, in order.

TYPE: tuple of Atom DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

conclusion

Its conclusion.

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

schematic

Variables fresh at every use, such as the type variables of a constant's scheme.

TYPE: tuple of str DEFAULT: ()

weight

The log weight of each application, zero by default.

TYPE: float DEFAULT: 0.0

line

The source position, zero when built in Python.

TYPE: int DEFAULT: 0

col

The source position, zero when built in Python.

TYPE: int DEFAULT: 0

ContextValue didactic-model

ContextValue(*, entries: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A context while solving: its entries, outermost first.

PARAMETER DESCRIPTION
entries

The values of the entries, possibly with unsolved variables.

TYPE: tuple of Pattern DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

Goal didactic-model

Goal(*, judgment: str, arguments: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A judgment instance to derive.

PARAMETER DESCRIPTION
judgment

The judgment.

TYPE: str

arguments

Its arguments; an output is a pattern, typically a fresh variable.

TYPE: tuple of GoalArgument DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

Derivation didactic-model

Derivation(*, rule: str, goal: Goal = field(opaque=True, extras=OPAQUE_BY_VALUE), premises: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), weight: float = 0.0)

Bases: ValueModel

A derivation found by the search.

PARAMETER DESCRIPTION
rule

The rule applied at the root.

TYPE: str

goal

The instance derived.

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

premises

The derivations of the premises.

TYPE: tuple of Derivation DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

weight

The rule's log weight.

TYPE: float DEFAULT: 0.0

JudgmentSystem

JudgmentSystem(signature: Signature, forms: Sequence[JudgmentForm], rules: Sequence[JudgmentRule], max_depth: int = 200)

The judgments of a signature, their rules, and their readings.

PARAMETER DESCRIPTION
signature

The signature of the terms.

TYPE: Signature

forms

The judgments.

TYPE: Sequence of JudgmentForm

rules

Their rules.

TYPE: Sequence of JudgmentRule

max_depth

The deepest derivation the search builds.

TYPE: int DEFAULT: 200

RAISES DESCRIPTION
JudgmentError

If a form or rule is ill-formed or ill-moded.

Source code in src/quivers/structural/theories/judgments.py
def __init__(
    self,
    signature: Signature,
    forms: Sequence[JudgmentForm],
    rules: Sequence[JudgmentRule],
    max_depth: int = 200,
) -> None:
    self.signature = signature
    self.forms: dict[str, JudgmentForm] = {}
    for form in forms:
        if form.name in self.forms or form.name == LOOKUP:
            raise JudgmentError(f"judgment {form.name!r} is declared twice")
        self.forms[form.name] = form
    self.rules = tuple(rules)
    self.max_depth = max_depth
    self._by_judgment: dict[str, list[JudgmentRule]] = {}
    for rule in self.rules:
        self._by_judgment.setdefault(rule.conclusion.judgment, []).append(rule)
    self._fresh = itertools.count()
    for form in self.forms.values():
        self._check_form(form)
    for rule in self.rules:
        self._check_rule(rule)
        check_modes(rule, self)

scoped_position

scoped_position(form: JudgmentForm) -> int | None

The argument a judgment's context scopes.

PARAMETER DESCRIPTION
form

The form.

TYPE: JudgmentForm

RETURNS DESCRIPTION
int or None

The position of the first non-context argument whose sort has variables, or None when the form has no context or none.

Source code in src/quivers/structural/theories/judgments.py
def scoped_position(self, form: JudgmentForm) -> int | None:
    """The argument a judgment's context scopes.

    Parameters
    ----------
    form : JudgmentForm
        The form.

    Returns
    -------
    int or None
        The position of the first non-context argument whose sort has
        variables, or ``None`` when the form has no context or none.
    """
    if not any(a.context for a in form.arguments):
        return None
    variable_sorts = set(self.signature.variable_sorts)
    for position, argument in enumerate(form.arguments):
        if not argument.context and argument.sort in variable_sorts:
            return position
    return None

goal

goal(judgment: str, *arguments: GoalArgument | None) -> Goal

A goal with a fresh variable at each output given as None.

PARAMETER DESCRIPTION
judgment

The judgment.

TYPE: str

*arguments

The inputs, and None for each output to compute.

TYPE: GoalArgument or None DEFAULT: ()

RETURNS DESCRIPTION
Goal

The goal.

RAISES DESCRIPTION
JudgmentError

If the arity is wrong.

Source code in src/quivers/structural/theories/judgments.py
def goal(self, judgment: str, *arguments: GoalArgument | None) -> Goal:
    """A goal with a fresh variable at each output given as ``None``.

    Parameters
    ----------
    judgment : str
        The judgment.
    *arguments : GoalArgument or None
        The inputs, and ``None`` for each output to compute.

    Returns
    -------
    Goal
        The goal.

    Raises
    ------
    JudgmentError
        If the arity is wrong.
    """
    form = self._form(judgment)
    if len(arguments) != len(form.arguments):
        raise JudgmentError(
            f"{judgment} takes {len(form.arguments)} arguments, got {len(arguments)}"
        )
    values: list[GoalArgument] = []
    for argument, declared in zip(arguments, form.arguments, strict=True):
        if argument is None:
            values.append(Metavariable(name=f"?out{next(self._fresh)}"))
        else:
            values.append(argument)
    return Goal(judgment=judgment, arguments=tuple(values))

solve

solve(goal: Goal) -> Iterator[tuple[Derivation, UnificationProblem]]

Every derivation of a goal, with the unification state it needs.

PARAMETER DESCRIPTION
goal

The goal.

TYPE: Goal

YIELDS DESCRIPTION
tuple of Derivation and UnificationProblem

A derivation and the solution of the goal's variables; apply problem.full to read an output.

RAISES DESCRIPTION
JudgmentError

If the search exceeds max_depth.

Source code in src/quivers/structural/theories/judgments.py
def solve(self, goal: Goal) -> Iterator[tuple[Derivation, UnificationProblem]]:
    """Every derivation of a goal, with the unification state it needs.

    Parameters
    ----------
    goal : Goal
        The goal.

    Yields
    ------
    tuple of Derivation and UnificationProblem
        A derivation and the solution of the goal's variables; apply
        ``problem.full`` to read an output.

    Raises
    ------
    JudgmentError
        If the search exceeds ``max_depth``.
    """
    sorts: dict = {}
    state = _State(UnificationProblem(self.signature, sorts), {}, {})
    for derivation, final in self._solve(goal, state, 0, _Failure()):
        yield derivation, final.problem

derivations

derivations(goal: Goal, limit: int | None = None) -> tuple[tuple[Derivation, UnificationProblem], ...]

Every derivation of a goal, or the failure that explains none.

PARAMETER DESCRIPTION
goal

The goal.

TYPE: Goal

limit

Stop after this many derivations.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
tuple

The derivations with their solutions, at least one.

RAISES DESCRIPTION
JudgmentFailure

If the goal has no derivation; the message is the constraint the deepest attempt could not satisfy.

Source code in src/quivers/structural/theories/judgments.py
def derivations(
    self, goal: Goal, limit: int | None = None
) -> tuple[tuple[Derivation, UnificationProblem], ...]:
    """Every derivation of a goal, or the failure that explains none.

    Parameters
    ----------
    goal : Goal
        The goal.
    limit : int or None
        Stop after this many derivations.

    Returns
    -------
    tuple
        The derivations with their solutions, at least one.

    Raises
    ------
    JudgmentFailure
        If the goal has no derivation; the message is the constraint
        the deepest attempt could not satisfy.
    """
    failure = _Failure()
    sorts: dict = {}
    state = _State(UnificationProblem(self.signature, sorts), {}, {})
    found: list[tuple[Derivation, UnificationProblem]] = []
    for derivation, final in self._solve(goal, state, 0, failure):
        found.append((derivation, final.problem))
        if limit is not None and len(found) >= limit:
            break
    if not found:
        raise JudgmentFailure(failure.message)
    return tuple(found)

infer

infer(judgment: str, *arguments: GoalArgument | None) -> tuple[tuple[PatternArgument, ...], ...]

The outputs of every derivation of a goal.

PARAMETER DESCRIPTION
judgment

The judgment.

TYPE: str

*arguments

Inputs, with None at each output.

TYPE: GoalArgument or None DEFAULT: ()

RETURNS DESCRIPTION
tuple of tuple of PatternArgument

One tuple of outputs per derivation, with unsolved variables left as metavariables; an output of a data sort is its data value.

RAISES DESCRIPTION
JudgmentFailure

If the goal has no derivation; the message is the constraint the deepest attempt could not satisfy.

Source code in src/quivers/structural/theories/judgments.py
def infer(
    self, judgment: str, *arguments: GoalArgument | None
) -> tuple[tuple[PatternArgument, ...], ...]:
    """The outputs of every derivation of a goal.

    Parameters
    ----------
    judgment : str
        The judgment.
    *arguments : GoalArgument or None
        Inputs, with ``None`` at each output.

    Returns
    -------
    tuple of tuple of PatternArgument
        One tuple of outputs per derivation, with unsolved variables
        left as metavariables; an output of a data sort is its data
        value.

    Raises
    ------
    JudgmentFailure
        If the goal has no derivation; the message is the constraint
        the deepest attempt could not satisfy.
    """
    goal = self.goal(judgment, *arguments)
    failure = _Failure()
    sorts: dict = {}
    state = _State(UnificationProblem(self.signature, sorts), {}, {})
    found: list[tuple[PatternArgument, ...]] = []
    outputs = [
        position
        for position, a in enumerate(self._form(judgment).arguments)
        if a.mode == "out"
    ]
    for _derivation, final in self._solve(goal, state, 0, failure):
        values = []
        for position in outputs:
            values.append(final.problem.full(goal.arguments[position]))
        found.append(tuple(values))
    if not found:
        raise JudgmentFailure(failure.message)
    return tuple(found)

chart

chart(goal: Goal, semiring: ChartSemiring, weights: Mapping[str, float] | None = None) -> dict[tuple, Tensor]

Run a goal's derivations on the agenda chart under a semiring.

Every derivation the search finds is read as ground hyperedges: an item is a judgment instance with its variables named in order of appearance, and an edge is a rule application. The agenda engine then computes each item's semiring value, the sum over its derivations of the product of their rule weights, so the derivations are not enumerated twice in the semiring.

PARAMETER DESCRIPTION
goal

The goal.

TYPE: Goal

semiring

The semiring.

TYPE: ChartSemiring

weights

Log weights by rule name, overriding the declared ones.

TYPE: Mapping of str to float or None DEFAULT: None

RETURNS DESCRIPTION
dict of tuple to torch.Tensor

The value of every item that instantiates the goal, keyed by the item.

Source code in src/quivers/structural/theories/judgments.py
def chart(
    self,
    goal: Goal,
    semiring: ChartSemiring,
    weights: Mapping[str, float] | None = None,
) -> dict[tuple, torch.Tensor]:
    """Run a goal's derivations on the agenda chart under a semiring.

    Every derivation the search finds is read as ground hyperedges:
    an item is a judgment instance with its variables named in order
    of appearance, and an edge is a rule application. The agenda
    engine then computes each item's semiring value, the sum over its
    derivations of the product of their rule weights, so the
    derivations are not enumerated twice in the semiring.

    Parameters
    ----------
    goal : Goal
        The goal.
    semiring : ChartSemiring
        The semiring.
    weights : Mapping of str to float or None
        Log weights by rule name, overriding the declared ones.

    Returns
    -------
    dict of tuple to torch.Tensor
        The value of every item that instantiates the goal, keyed by
        the item.
    """
    edges: dict[tuple, tuple[str, tuple[tuple, ...], float]] = {}
    roots: set[tuple] = set()
    for derivation, problem in self.solve(goal):
        roots.add(self._edges(derivation, problem, edges, weights or {}))
    axioms: list[tuple[tuple, torch.Tensor]] = []
    rules: list[InferenceRule] = []
    for key, (rule, premises, weight) in edges.items():
        conclusion = key[1]
        element = torch.tensor(
            weight if semiring.log_weights else semiring.one,
            dtype=torch.float64,
        )
        if not premises:
            axioms.append((conclusion, element))
            continue
        rules.append(
            InferenceRule(
                name=rule,
                premises=premises,
                conclusion=conclusion,
                weight_fn=_weighted(element),
            )
        )
    result = run_agenda(axioms, rules, semiring=semiring)
    return {item: weight for item, weight in result.chart.items() if item in roots}

build_atom

build_atom(syntax: PatternSyntax, forms: Mapping[str, JudgmentForm], signature: Signature) -> Atom

Resolve a written judgment instance J(a_1, ..., a_n) to an atom.

A context argument is a context variable or an extension (ctx, x : A); the names an extension adds are bound in the scoped argument of the same instance, where S.var(i) is a variable of the scoped sort S with index i. Every other name is resolved by quivers.structural.patterns.resolve.

PARAMETER DESCRIPTION
syntax

The written instance.

TYPE: PatternSyntax

forms

The declared judgments.

TYPE: Mapping of str to JudgmentForm

signature

The signature.

TYPE: Signature

RETURNS DESCRIPTION
Atom

The atom.

RAISES DESCRIPTION
JudgmentError

If the judgment is undeclared, the arity is wrong, or an argument has the wrong form for its position.

Source code in src/quivers/structural/theories/judgments.py
def build_atom(
    syntax: PatternSyntax,
    forms: Mapping[str, JudgmentForm],
    signature: Signature,
) -> Atom:
    """Resolve a written judgment instance ``J(a_1, ..., a_n)`` to an atom.

    A context argument is a context variable or an extension
    ``(ctx, x : A)``; the names an extension adds are bound in the scoped
    argument of the same instance, where ``S.var(i)`` is a variable of the
    scoped sort ``S`` with index ``i``. Every other name is resolved by
    `quivers.structural.patterns.resolve`.

    Parameters
    ----------
    syntax : PatternSyntax
        The written instance.
    forms : Mapping of str to JudgmentForm
        The declared judgments.
    signature : Signature
        The signature.

    Returns
    -------
    Atom
        The atom.

    Raises
    ------
    JudgmentError
        If the judgment is undeclared, the arity is wrong, or an argument
        has the wrong form for its position.
    """
    if syntax.kind != "apply":
        raise JudgmentError(
            "a premise or conclusion is a judgment applied to arguments"
        )
    if syntax.name == LOOKUP:
        if len(syntax.args) != 3:
            raise JudgmentError("lookup(ctx, i, A) takes three arguments")
        context, index, entry = syntax.args
        if context.kind != "name" or index.kind != "name":
            raise JudgmentError("lookup(ctx, i, A) takes a context and an index name")
        return Atom(
            judgment=LOOKUP,
            arguments=(
                ContextPattern(base=context.name),
                Metavariable(name=index.name),
                _resolve_closed(entry, signature),
            ),
        )
    form = forms.get(syntax.name)
    if form is None:
        raise JudgmentError(f"judgment {syntax.name!r} is not declared")
    if len(syntax.args) != len(form.arguments):
        raise JudgmentError(
            f"{syntax.name} takes {len(form.arguments)} arguments, got {len(syntax.args)}"
        )
    variable_sorts = set(signature.variable_sorts)
    scope: tuple[str, ...] = ()
    arguments: list[AtomArgument] = []
    for argument, declared in zip(syntax.args, form.arguments, strict=True):
        if not declared.context:
            continue
        if argument.kind == "name":
            continue
        if argument.kind != "extend":
            raise JudgmentError(
                f"argument {declared.name!r} of {syntax.name} is a context: a context "
                "name or an extension `(ctx, x : A)`"
            )
        scope = argument.names
    scoped_done = False
    for argument, declared in zip(syntax.args, form.arguments, strict=True):
        if declared.context:
            if argument.kind == "name":
                arguments.append(ContextPattern(base=argument.name))
            else:
                arguments.append(
                    ContextPattern(
                        base=argument.name,
                        names=argument.names,
                        types=tuple(
                            _resolve_closed(t, signature) for t in argument.args
                        ),
                    )
                )
            continue
        if (
            not scoped_done
            and declared.sort in variable_sorts
            and any(a.context for a in form.arguments)
        ):
            scoped_done = True
            if argument.kind == "apply" and argument.name == (
                f"{declared.sort}.{VARIABLE}"
            ):
                if len(argument.args) != 1 or argument.args[0].kind != "name":
                    raise JudgmentError(
                        f"{argument.name}(i) names the variable's index"
                    )
                arguments.append(
                    VariablePattern(sort=declared.sort, index=argument.args[0].name)
                )
                continue
            try:
                resolved = resolve(argument, signature, scope)
            except PatternError as error:
                raise JudgmentError(str(error)) from error
            if not isinstance(
                resolved, PatternApplication | Metavariable | PatternVariable
            ):
                raise JudgmentError(f"argument {declared.name!r} is a term")
            arguments.append(resolved)
            continue
        arguments.append(_resolve_closed(argument, signature))
    return Atom(judgment=syntax.name, arguments=tuple(arguments))

rule_from_text

rule_from_text(name: str, text: str, forms: Mapping[str, JudgmentForm], signature: Signature, *, schematic: tuple[str, ...] = (), weight: float = 0.0) -> JudgmentRule

Read a rule written P_1, ..., P_n |- C.

PARAMETER DESCRIPTION
name

The rule's name.

TYPE: str

text

The premises, |-, and the conclusion.

TYPE: str

forms

The declared judgments.

TYPE: Mapping of str to JudgmentForm

signature

The signature.

TYPE: Signature

schematic

Variables fresh at each use.

TYPE: tuple of str DEFAULT: ()

weight

The rule's log weight.

TYPE: float DEFAULT: 0.0

RETURNS DESCRIPTION
JudgmentRule

The rule.

RAISES DESCRIPTION
JudgmentError

If the text is not a rule.

Source code in src/quivers/structural/theories/judgments.py
def rule_from_text(
    name: str,
    text: str,
    forms: Mapping[str, JudgmentForm],
    signature: Signature,
    *,
    schematic: tuple[str, ...] = (),
    weight: float = 0.0,
) -> JudgmentRule:
    """Read a rule written ``P_1, ..., P_n |- C``.

    Parameters
    ----------
    name : str
        The rule's name.
    text : str
        The premises, ``|-``, and the conclusion.
    forms : Mapping of str to JudgmentForm
        The declared judgments.
    signature : Signature
        The signature.
    schematic : tuple of str
        Variables fresh at each use.
    weight : float
        The rule's log weight.

    Returns
    -------
    JudgmentRule
        The rule.

    Raises
    ------
    JudgmentError
        If the text is not a rule.
    """
    if "|-" not in text:
        raise JudgmentError(
            f"rule {name!r}: a rule is written `premises |- conclusion`"
        )
    before, after = text.split("|-", 1)
    premises: list[Atom] = []
    if before.strip():
        try:
            written = parse_pattern(f"Premises({before})")
        except PatternError as error:
            raise JudgmentError(f"rule {name!r}: {error}") from error
        premises = [build_atom(p, forms, signature) for p in written.args]
    try:
        conclusion = build_atom(parse_pattern(after.strip()), forms, signature)
    except PatternError as error:
        raise JudgmentError(f"rule {name!r}: {error}") from error
    return JudgmentRule(
        name=name,
        premises=tuple(premises),
        conclusion=conclusion,
        schematic=schematic,
        weight=weight,
    )

check_modes

check_modes(rule: JudgmentRule, system: JudgmentSystem) -> None

Refuse a rule whose outputs its premises do not determine.

The conclusion's inputs determine their variables. Each premise, read left to right, determines every variable it mentions: an input variable not yet determined becomes a unification variable, which the premise's derivation constrains. Every variable of the conclusion's outputs must then be determined, unless the rule declares it in its bracket telescope as fresh at each use. A premise's scoped term argument and the index of a lookup must be determined before the premise, since they are matched rather than unified.

PARAMETER DESCRIPTION
rule

The rule.

TYPE: JudgmentRule

system

Its system.

TYPE: JudgmentSystem

RAISES DESCRIPTION
JudgmentError

If an output variable is undetermined or a premise's scoped input is not yet determined; the message names the variable and the rule.

Source code in src/quivers/structural/theories/judgments.py
def check_modes(rule: JudgmentRule, system: JudgmentSystem) -> None:
    """Refuse a rule whose outputs its premises do not determine.

    The conclusion's inputs determine their variables. Each premise, read
    left to right, determines every variable it mentions: an input
    variable not yet determined becomes a unification variable, which the
    premise's derivation constrains. Every variable of the conclusion's
    outputs must then be determined, unless the rule declares it in its
    bracket telescope as fresh at each use. A premise's scoped term
    argument and the index of a ``lookup`` must be determined before the
    premise, since they are matched rather than unified.

    Parameters
    ----------
    rule : JudgmentRule
        The rule.
    system : JudgmentSystem
        Its system.

    Raises
    ------
    JudgmentError
        If an output variable is undetermined or a premise's scoped input
        is not yet determined; the message names the variable and the rule.
    """
    known: set[str] = set(rule.schematic)
    conclusion_form = system._form(rule.conclusion.judgment)
    for argument, declared in zip(
        rule.conclusion.arguments, conclusion_form.arguments, strict=True
    ):
        if declared.mode == "in":
            known |= _names(argument)
    for premise in rule.premises:
        if premise.judgment == LOOKUP:
            context, index, entry = premise.arguments
            assert isinstance(index, Metavariable)
            if index.name not in known:
                raise JudgmentError(
                    f"rule {rule.name!r}: the index {index.name!r} of lookup is not "
                    "determined before the premise"
                )
            known |= _names(context) | _names(entry)
            continue
        form = system._form(premise.judgment)
        scoped = system.scoped_position(form)
        for position, (argument, declared) in enumerate(
            zip(premise.arguments, form.arguments, strict=True)
        ):
            if position == scoped and declared.mode == "in":
                missing = sorted(_names(argument) - known)
                if missing:
                    raise JudgmentError(
                        f"rule {rule.name!r}: variable {missing[0]!r} of the term "
                        f"argument of premise {premise.judgment} is not determined "
                        "before the premise"
                    )
        for argument in premise.arguments:
            known |= _names(argument)
    for argument, declared in zip(
        rule.conclusion.arguments, conclusion_form.arguments, strict=True
    ):
        if declared.mode != "out":
            continue
        missing = sorted(_names(argument) - known)
        if missing:
            raise JudgmentError(
                f"rule {rule.name!r}: output variable {missing[0]!r} of "
                f"{rule.conclusion.judgment} is not determined by the conclusion's "
                "inputs or the premises; derive it in a premise or declare it in the "
                f"rule's telescope as `rule {rule.name}[{missing[0]}]` to make it "
                "fresh at each use"
            )

probability_weights

probability_weights(probabilities: Mapping[str, float]) -> dict[str, float]

Log weights for rules given as probabilities.

PARAMETER DESCRIPTION
probabilities

A probability per rule.

TYPE: Mapping of str to float

RETURNS DESCRIPTION
dict of str to float

Their logarithms.

RAISES DESCRIPTION
JudgmentError

If a probability is not positive.

Source code in src/quivers/structural/theories/judgments.py
def probability_weights(probabilities: Mapping[str, float]) -> dict[str, float]:
    """Log weights for rules given as probabilities.

    Parameters
    ----------
    probabilities : Mapping of str to float
        A probability per rule.

    Returns
    -------
    dict of str to float
        Their logarithms.

    Raises
    ------
    JudgmentError
        If a probability is not positive.
    """
    found: dict[str, float] = {}
    for name, value in probabilities.items():
        if value <= 0:
            raise JudgmentError(f"rule {name!r} has non-positive probability {value}")
        found[name] = math.log(value)
    return found