Skip to content

Deduction composition

Deduction signatures, lexicon modules, and rule schemata, composed into ordinary deductions; the item families of signatures, their inclusions and copaired folds; and the classification of an extension. The reference describes the surface, and the semantics states the rules.

deduction_composition

Compose deductions from signatures, lexicon modules, and rule schemata.

A deduction may extend deduction signatures and take lexicon modules:

deduction signature CCGCore
    atoms S, NP, N, Fwd, Bwd, span
    rule fwd_app : span(I, K, Fwd(X, Y)), span(K, J, Y) |- span(I, J, X)

lexicon Nouns for CCGCore
    atoms dog
    "dog" : N = dog

deduction Grammar : Word -> Word [start=S]
    extends CCGCore, Composition[n <= 1]
    lexicon Nouns

compose_deductions interprets every such deduction statically as one monolithic deduction whose atoms, rules, and lexicon are the union of its parts, so every engine (the checked elaboration, the compiled agenda, each transpile target) sees exactly the deduction a user could have written by hand. The union is a colimit over the shared parts, by origin:

  • an atom (and every rule) belongs to the declaration that introduces it. A signature reached along two paths (Grammar extends A and B, both extending Base) contributes its atoms once; two different declarations introducing one name are two atoms and are refused, never merged because their spellings coincide;
  • a lexicon module is typed against a signature: every atom its entries' categories use is an atom of that signature or of a signature it extends, and the deduction taking it must extend that signature;
  • a signature's rules apply only atoms it declares or includes, and a rule's identifiers are resolved where the rule is written: an atom declared downstream, by an extension or a lexicon, never captures one of its pattern variables or bound names, which are renamed apart from every atom of the composed deduction (_hygienic).

Rule schemata (quivers.dsl.deduction_schemata) are instantiated over the composed rule set: a rules line in a signature or in the deduction names any schema in scope, and extends S[c] keeps, of the instances of the schemata declared in S (and the signatures S extends), those whose parameters satisfy c.

The composed deduction records where each symbol was declared (origins) and the signatures it extends (cores), whose atoms are the constructors of the signature's own item family S.Item: the core a generic reader of any extension observes, and the domain of the inclusion S.Item -> Grammar.Item along which reification is natural.

CompositionError

CompositionError(message: str, line: int, col: int)

Bases: ValueError

A deduction whose parts do not compose.

PARAMETER DESCRIPTION
message

What is wrong.

TYPE: str

line

Where.

TYPE: int

col

Where.

TYPE: int

Source code in src/quivers/dsl/deduction_composition.py
def __init__(self, message: str, line: int, col: int) -> None:
    super().__init__(message)
    self.line = line
    self.col = col

compose_deductions

compose_deductions(module: Module) -> Module

Interpret every composed deduction as one monolithic deduction.

PARAMETER DESCRIPTION
module

A flat module.

TYPE: Module

RETURNS DESCRIPTION
Module

The module itself when no statement is composed; otherwise the module with every deduction composed, and its deduction signatures, lexicon modules, and exports of them removed (they denote no code of their own).

RAISES DESCRIPTION
CompositionError

If a part is unknown, atoms or rules of different origins share a name, a lexicon entry's category uses an atom its signature lacks, a signature rule applies an atom the signature lacks, or a schema or its instantiation is ill-formed.

Source code in src/quivers/dsl/deduction_composition.py
def compose_deductions(module: Module) -> Module:
    """Interpret every composed deduction as one monolithic deduction.

    Parameters
    ----------
    module : Module
        A flat module.

    Returns
    -------
    Module
        The module itself when no statement is composed; otherwise the
        module with every deduction composed, and its deduction signatures,
        lexicon modules, and exports of them removed (they denote no code
        of their own).

    Raises
    ------
    CompositionError
        If a part is unknown, atoms or rules of different origins share a
        name, a lexicon entry's category uses an atom its signature lacks,
        a signature rule applies an atom the signature lacks, or a schema
        or its instantiation is ill-formed.
    """
    if not any(_needs_composition(statement) for statement in module.statements):
        return module
    signatures = {
        statement.name: statement
        for statement in module.statements
        if isinstance(statement, DeductionSignatureDecl)
    }
    lexicons = {
        statement.name: statement
        for statement in module.statements
        if isinstance(statement, LexiconDecl)
    }
    deductions = frozenset(
        statement.name
        for statement in module.statements
        if isinstance(statement, DeductionDecl)
    )
    sorts = {
        statement.name: statement
        for statement in module.statements
        if isinstance(statement, QiecIndexDecl)
    }
    for signature in signatures.values():
        _check_signature(signature, signatures, lexicons, deductions, sorts)
    removed = frozenset((*signatures, *lexicons))
    statements: list[Statement] = []
    for statement in module.statements:
        if isinstance(statement, DeductionSignatureDecl | LexiconDecl):
            continue
        if (
            isinstance(statement, ExportDecl)
            and isinstance(statement.expr, ExprIdent)
            and statement.expr.name in removed
        ):
            continue
        if isinstance(statement, DeductionDecl) and _needs_composition(statement):
            statement = _compose(statement, signatures, lexicons, deductions, sorts)
        statements.append(statement)
    try:
        return reify_cores(module.with_(statements=tuple(statements)))
    except ReificationError as error:
        raise CompositionError(str(error), error.line, error.col) from error

deduction_schemata

Rule schemata: families of deduction rules indexed by static parameters.

A rule with a static telescope, rule r[n : Nat, e : Dir] : ..., is a schema: one rule for every assignment of its parameters. A rules line instantiates it at the assignments its constraints admit,

rules r[n <= 2, e in Dir] where not (n == 0 && e == Bwd)

and each instance is an ordinary rule, so it takes part in the chart exactly as a hand-written rule would. A parameter ranges over its sort: Bool over false and true, a declared index sort over its constructors (each must be nullary), and Nat over the numerals a bracketed bound (n <= 2, n < 3, n == 1) admits. Membership constraints (e in {Fwd}) narrow a domain; every other constraint, and the where condition, is a Boolean condition on the assignment.

Instantiation substitutes an assignment into the schema's patterns. A parameter standing for an index value is the deduction atom of the same spelling, in argument position or as the head of an application (e(X, Y) is Fwd(X, Y) at e = Fwd); a numeral parameter is a numeral. A slash spine Y |e Z ... n is the category Y taking the n arguments Z_1 ... Z_n through the slash e, that is e(...e(e(Y, Z_1), Z_2)..., Z_n); every spine over the same sequence variable in one rule has the same length, so a premise and the conclusion share the arguments. A name sequence z ... n, the first of an application's two arguments, folds the application to the right: e(z ... n, B) is B at n = 0 and e(z_1, e(z_2, ... e(z_n, B))) otherwise, so Lam(z ... n, App(F, G |App z ... n)) binds the names the spine applies G to, the composition combinator of degree n. A sequence shares its variable's length with the rule's spines.

Each instance is named r_v1_..._vk (the parameters' values in telescope order). The #[shared = F(p, ...)] pragma makes the rule's weight the learnable weight family F at the index the parameters take, so instances that agree on that index read one weight; its key is shared_weight_key.

SHARED_OPTION module-attribute

SHARED_OPTION = 'shared'

The option key naming a rule's shared weight family.

SchemaValue

SchemaValue = int | bool | str

A value of a schema parameter: a numeral, a Boolean, or an index value.

SchemaError

SchemaError(message: str, line: int, col: int)

Bases: ValueError

A rule schema or instantiation that does not denote a finite rule set.

PARAMETER DESCRIPTION
message

What is wrong.

TYPE: str

line

Where.

TYPE: int

col

Where.

TYPE: int

Source code in src/quivers/dsl/deduction_schemata.py
def __init__(self, message: str, line: int, col: int) -> None:
    super().__init__(message)
    self.line = line
    self.col = col

render_value

render_value(value: SchemaValue) -> str

The spelling of a parameter value in names and patterns.

PARAMETER DESCRIPTION
value

The value.

TYPE: SchemaValue

RETURNS DESCRIPTION
str

true/false, the numeral, or the index value's name.

Source code in src/quivers/dsl/deduction_schemata.py
def render_value(value: SchemaValue) -> str:
    """The spelling of a parameter value in names and patterns.

    Parameters
    ----------
    value : SchemaValue
        The value.

    Returns
    -------
    str
        ``true``/``false``, the numeral, or the index value's name.
    """
    if isinstance(value, bool):
        return "true" if value else "false"
    return str(value)

schema_parameters

schema_parameters(rule: SequentRule) -> tuple[QiecIndexBinder, ...]

A schema's parameters, refusing a binder that is not over an index sort.

PARAMETER DESCRIPTION
rule

A rule; a rule with no telescope has no parameters.

TYPE: SequentRule

RETURNS DESCRIPTION
tuple[QiecIndexBinder, ...]

Its parameters, in telescope order.

RAISES DESCRIPTION
SchemaError

If the telescope binds a type, an effect, or a row: a schema's parameters range over finite static domains.

Source code in src/quivers/dsl/deduction_schemata.py
def schema_parameters(rule: SequentRule) -> tuple[QiecIndexBinder, ...]:
    """A schema's parameters, refusing a binder that is not over an index sort.

    Parameters
    ----------
    rule : SequentRule
        A rule; a rule with no telescope has no parameters.

    Returns
    -------
    tuple[QiecIndexBinder, ...]
        Its parameters, in telescope order.

    Raises
    ------
    SchemaError
        If the telescope binds a type, an effect, or a row: a schema's
        parameters range over finite static domains.
    """
    parameters: list[QiecIndexBinder] = []
    for binder in rule.parameters:
        if not isinstance(binder, QiecIndexBinder):
            raise SchemaError(
                f"rule schema {rule.name!r}: its telescope binds a type, an effect, "
                "or a row; a schema's parameters range over Nat, Bool, or an index "
                "sort",
                rule.line,
                rule.col,
            )
        parameters.append(binder)
    return tuple(parameters)

constraint_location

constraint_location(constraint: SchemaConstraint, line: int, col: int) -> tuple[int, int]

Where a constraint is written, or the given location if unknown.

PARAMETER DESCRIPTION
constraint

The constraint.

TYPE: SchemaConstraint

line

The location to report when the constraint carries none.

TYPE: int

col

The location to report when the constraint carries none.

TYPE: int

RETURNS DESCRIPTION
tuple[int, int]

The line and the column.

Source code in src/quivers/dsl/deduction_schemata.py
def constraint_location(
    constraint: SchemaConstraint, line: int, col: int
) -> tuple[int, int]:
    """Where a constraint is written, or the given location if unknown.

    Parameters
    ----------
    constraint : SchemaConstraint
        The constraint.
    line, col : int
        The location to report when the constraint carries none.

    Returns
    -------
    tuple[int, int]
        The line and the column.
    """
    if isinstance(constraint, SchemaMembership | SchemaCondition) and constraint.line:
        return constraint.line, constraint.col
    return line, col

evaluate_condition

evaluate_condition(node: LetExprNode, environment: Mapping[str, SchemaValue], values: frozenset[str], where: tuple[str, int, int]) -> SchemaValue

Evaluate a constraint over one assignment.

PARAMETER DESCRIPTION
node

The expression.

TYPE: LetExprNode

environment

The parameters' values.

TYPE: Mapping[str, SchemaValue]

values

The index values in scope, which a name may spell.

TYPE: frozenset[str]

where

The schema's name and the instantiation's location, for refusals.

TYPE: tuple[str, int, int]

RETURNS DESCRIPTION
SchemaValue

The expression's value.

RAISES DESCRIPTION
SchemaError

If the expression uses a name that is neither a parameter nor an index value, an operator outside comparisons, arithmetic, and the Boolean connectives, or operands of the wrong kind.

Source code in src/quivers/dsl/deduction_schemata.py
def evaluate_condition(
    node: LetExprNode,
    environment: Mapping[str, SchemaValue],
    values: frozenset[str],
    where: tuple[str, int, int],
) -> SchemaValue:
    """Evaluate a constraint over one assignment.

    Parameters
    ----------
    node : LetExprNode
        The expression.
    environment : Mapping[str, SchemaValue]
        The parameters' values.
    values : frozenset[str]
        The index values in scope, which a name may spell.
    where : tuple[str, int, int]
        The schema's name and the instantiation's location, for refusals.

    Returns
    -------
    SchemaValue
        The expression's value.

    Raises
    ------
    SchemaError
        If the expression uses a name that is neither a parameter nor an
        index value, an operator outside comparisons, arithmetic, and the
        Boolean connectives, or operands of the wrong kind.
    """
    schema, line, col = where

    def fail(message: str) -> SchemaError:
        return SchemaError(f"rules {schema}: {message}", line, col)

    if isinstance(node, LetExprLiteral):
        if not node.integral:
            raise fail(f"the numeral {node.value!r} is not a natural number")
        return int(node.value)
    if isinstance(node, LetExprBool):
        return bool(node.value)
    if isinstance(node, LetExprVar):
        if node.name in environment:
            return environment[node.name]
        if node.name in values:
            return node.name
        raise fail(
            f"{node.name!r} is neither a parameter of the schema nor a value of "
            "one of its index sorts"
        )
    if isinstance(node, LetExprUnaryOp):
        operand = evaluate_condition(node.operand, environment, values, where)
        if node.op == "not":
            if not isinstance(operand, bool):
                raise fail("`not` applies to a Boolean")
            return not operand
        if isinstance(operand, bool) or not isinstance(operand, int):
            raise fail("`-` applies to a number")
        return -operand
    if isinstance(node, LetExprBinOp):
        left = evaluate_condition(node.left, environment, values, where)
        right = evaluate_condition(node.right, environment, values, where)
        if node.op in ("&&", "||"):
            if not isinstance(left, bool) or not isinstance(right, bool):
                raise fail(f"`{node.op}` joins Boolean conditions")
            return (left and right) if node.op == "&&" else (left or right)
        if node.op in ("==", "!="):
            if type(left) is not type(right):
                raise fail(
                    f"`{node.op}` compares {render_value(left)!r} with "
                    f"{render_value(right)!r}, values of different sorts"
                )
            return (left == right) if node.op == "==" else (left != right)
        numeric = (
            isinstance(left, int)
            and not isinstance(left, bool)
            and isinstance(right, int)
            and not isinstance(right, bool)
        )
        if not numeric:
            raise fail(f"`{node.op}` applies to numbers")
        assert isinstance(left, int) and isinstance(right, int)
        operations: dict[str, Callable[[int, int], SchemaValue]] = {
            "<": lambda a, b: a < b,
            "<=": lambda a, b: a <= b,
            ">": lambda a, b: a > b,
            ">=": lambda a, b: a >= b,
            "+": lambda a, b: a + b,
            "-": lambda a, b: a - b,
            "*": lambda a, b: a * b,
        }
        operation = operations.get(node.op)
        if operation is None:
            raise fail(f"the operator `{node.op}` has no meaning on parameters")
        return operation(left, right)
    raise fail(f"a {node.kind} expression has no meaning on parameters")

assignments

assignments(rule: SequentRule, instantiation: RuleInstantiation, sorts: Mapping[str, QiecIndexDecl], restrictions: tuple[SchemaConstraint, ...] = ()) -> Iterator[tuple[SchemaValue, ...]]

Every assignment of a schema's parameters an instantiation admits.

PARAMETER DESCRIPTION
rule

The schema.

TYPE: SequentRule

instantiation

The rules entry.

TYPE: RuleInstantiation

sorts

The module's index sorts.

TYPE: Mapping[str, QiecIndexDecl]

restrictions

Further constraints from an extends S[...] restriction; each applies only when the schema has every parameter it mentions.

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

YIELDS DESCRIPTION
tuple[SchemaValue, ...]

One value per parameter, in telescope order, in the order of the domains (numerals ascending, index values in declaration order).

RAISES DESCRIPTION
SchemaError

If a constraint names no parameter, a domain is infinite or unknown, or a condition is ill-formed.

Source code in src/quivers/dsl/deduction_schemata.py
def assignments(
    rule: SequentRule,
    instantiation: RuleInstantiation,
    sorts: Mapping[str, QiecIndexDecl],
    restrictions: tuple[SchemaConstraint, ...] = (),
) -> Iterator[tuple[SchemaValue, ...]]:
    """Every assignment of a schema's parameters an instantiation admits.

    Parameters
    ----------
    rule : SequentRule
        The schema.
    instantiation : RuleInstantiation
        The ``rules`` entry.
    sorts : Mapping[str, QiecIndexDecl]
        The module's index sorts.
    restrictions : tuple[SchemaConstraint, ...]
        Further constraints from an ``extends S[...]`` restriction; each
        applies only when the schema has every parameter it mentions.

    Yields
    ------
    tuple[SchemaValue, ...]
        One value per parameter, in telescope order, in the order of the
        domains (numerals ascending, index values in declaration order).

    Raises
    ------
    SchemaError
        If a constraint names no parameter, a domain is infinite or
        unknown, or a condition is ill-formed.
    """
    parameters = schema_parameters(rule)
    names = [binder.name for binder in parameters]
    where = (instantiation.schema, instantiation.line, instantiation.col)
    for constraint in instantiation.constraints:
        mentioned = constraint_names(constraint)
        unknown = sorted(mentioned - set(names) - index_values(sorts))
        if (
            isinstance(constraint, SchemaMembership)
            and constraint.parameter not in names
        ):
            unknown = [constraint.parameter]
        if unknown:
            raise SchemaError(
                f"rules {instantiation.schema}: schema {rule.name!r} has no "
                f"parameter {unknown[0]!r}; its parameters are {', '.join(names)}",
                *constraint_location(constraint, instantiation.line, instantiation.col),
            )
    applicable = tuple(
        constraint
        for constraint in restrictions
        if (constraint_names(constraint) - index_values(sorts)) <= set(names)
    )
    constraints = (*instantiation.constraints, *applicable)
    domains: list[tuple[SchemaValue, ...]] = []
    for binder in parameters:
        domain = _domain(
            rule, binder, sorts, _nat_bound(binder.name, constraints), instantiation
        )
        for constraint in constraints:
            if not (
                isinstance(constraint, SchemaMembership)
                and constraint.parameter == binder.name
            ):
                continue
            if constraint.domain:
                if split_module(constraint.domain)[1] != _sort_name(binder):
                    raise SchemaError(
                        f"rules {instantiation.schema}: parameter {binder.name!r} "
                        f"ranges over {_sort_name(binder)}, not "
                        f"{constraint.domain!r}",
                        constraint.line,
                        constraint.col,
                    )
                continue
            outside = [
                element
                for element in constraint.elements
                if element not in {render_value(value) for value in domain}
            ]
            if outside:
                raise SchemaError(
                    f"rules {instantiation.schema}: {outside[0]!r} is no value of "
                    f"parameter {binder.name!r}, which ranges over "
                    f"{_sort_name(binder)}",
                    constraint.line,
                    constraint.col,
                )
            domain = tuple(
                value for value in domain if render_value(value) in constraint.elements
            )
        domains.append(domain)
    values = index_values(sorts)
    conditions = [
        constraint.condition
        for constraint in constraints
        if isinstance(constraint, SchemaCondition)
    ]
    if instantiation.condition is not None:
        conditions.append(instantiation.condition)
    for assignment in product(*domains):
        environment = dict(zip(names, assignment, strict=True))
        admitted = True
        for condition in conditions:
            verdict = evaluate_condition(condition, environment, values, where)
            if not isinstance(verdict, bool):
                raise SchemaError(
                    f"rules {instantiation.schema}: a constraint is "
                    f"{render_value(verdict)!r}, not a condition",
                    instantiation.line,
                    instantiation.col,
                )
            if not verdict:
                admitted = False
                break
        if admitted:
            yield assignment

index_values

index_values(sorts: Mapping[str, QiecIndexDecl]) -> frozenset[str]

Every nullary index constructor of the module.

PARAMETER DESCRIPTION
sorts

The module's index sorts.

TYPE: Mapping[str, QiecIndexDecl]

RETURNS DESCRIPTION
frozenset[str]

The names a constraint may use as values.

Source code in src/quivers/dsl/deduction_schemata.py
def index_values(sorts: Mapping[str, QiecIndexDecl]) -> frozenset[str]:
    """Every nullary index constructor of the module.

    Parameters
    ----------
    sorts : Mapping[str, QiecIndexDecl]
        The module's index sorts.

    Returns
    -------
    frozenset[str]
        The names a constraint may use as values.
    """
    return frozenset(
        split_module(item.name)[1]
        for declared in sorts.values()
        for item in declared.constructors
        if not item.arguments
    )

constraint_names

constraint_names(constraint: SchemaConstraint) -> set[str]

The names a constraint mentions.

PARAMETER DESCRIPTION
constraint

A constraint.

TYPE: SchemaConstraint

RETURNS DESCRIPTION
set[str]

The parameter of a membership; every variable of a condition.

Source code in src/quivers/dsl/deduction_schemata.py
def constraint_names(constraint: SchemaConstraint) -> set[str]:
    """The names a constraint mentions.

    Parameters
    ----------
    constraint : SchemaConstraint
        A constraint.

    Returns
    -------
    set[str]
        The parameter of a membership; every variable of a condition.
    """
    if isinstance(constraint, SchemaMembership):
        return {constraint.parameter}
    if isinstance(constraint, SchemaCondition):
        found: set[str] = set()
        stack: list[LetExprNode] = [constraint.condition]
        while stack:
            node = stack.pop()
            if isinstance(node, LetExprVar):
                found.add(node.name)
            elif isinstance(node, LetExprBinOp):
                stack.extend((node.left, node.right))
            elif isinstance(node, LetExprUnaryOp):
                stack.append(node.operand)
        return found
    return set()

instantiate

instantiate(rule: SequentRule, assignment: tuple[SchemaValue, ...]) -> SequentRule

The instance of a schema at one assignment.

PARAMETER DESCRIPTION
rule

The schema.

TYPE: SequentRule

assignment

One value per parameter, in telescope order.

TYPE: tuple[SchemaValue, ...]

RETURNS DESCRIPTION
SequentRule

The rule, with no parameters, named r_v1_..._vk.

RAISES DESCRIPTION
SchemaError

If a numeral or a Boolean heads an application or stands for a slash, a spine's or a name sequence's length is no numeral, two of them over one sequence variable differ in length, a name sequence is not the first of an application's two arguments, or a sequence variable's names would capture a name the rule already uses.

Source code in src/quivers/dsl/deduction_schemata.py
def instantiate(
    rule: SequentRule,
    assignment: tuple[SchemaValue, ...],
) -> SequentRule:
    """The instance of a schema at one assignment.

    Parameters
    ----------
    rule : SequentRule
        The schema.
    assignment : tuple[SchemaValue, ...]
        One value per parameter, in telescope order.

    Returns
    -------
    SequentRule
        The rule, with no parameters, named ``r_v1_..._vk``.

    Raises
    ------
    SchemaError
        If a numeral or a Boolean heads an application or stands for a
        slash, a spine's or a name sequence's length is no numeral, two of
        them over one sequence variable differ in length, a name sequence
        is not the first of an application's two arguments, or a sequence
        variable's names would capture a name the rule already uses.
    """
    parameters = schema_parameters(rule)
    environment = {
        binder.name: value for binder, value in zip(parameters, assignment, strict=True)
    }
    used: set[str] = set()
    for pattern in (*rule.premises, rule.conclusion):
        used |= _names(pattern)
    lengths: dict[str, str] = {}
    for pattern in (*rule.premises, rule.conclusion):
        for spine in _spines(pattern):
            known = lengths.setdefault(spine.argument, spine.length)
            if known != spine.length:
                raise SchemaError(
                    f"rule schema {rule.name!r}: the sequence variable "
                    f"{spine.argument!r} has length {known!r} in one place and "
                    f"{spine.length!r} in another",
                    spine.line,
                    spine.col,
                )
    for pattern in (*rule.premises, rule.conclusion):
        plain = _plain_names(pattern)
        clash = sorted(plain & set(lengths))
        if clash:
            raise SchemaError(
                f"rule schema {rule.name!r}: {clash[0]!r} is a sequence variable "
                "and cannot also be an ordinary pattern variable",
                rule.line,
                rule.col,
            )

    def value_of(name: str, line: int, col: int) -> SchemaValue:
        if name in environment:
            return environment[name]
        if name.isdigit():
            return int(name)
        return name

    def atom(name: str, role: str, line: int, col: int) -> str:
        value = value_of(name, line, col)
        if isinstance(value, bool) or isinstance(value, int):
            raise SchemaError(
                f"rule schema {rule.name!r}: {name!r} is "
                f"{render_value(value)!r} here, which cannot be {role}; only a "
                "value of an index sort can",
                line,
                col,
            )
        return value

    def names_of(sequence: ObjectSpine | ObjectSequence) -> tuple[TypeName, ...]:
        """The names ``z_1`` through ``z_n`` a sequence variable stands for."""
        length = value_of(sequence.length, sequence.line, sequence.col)
        if isinstance(length, bool) or not isinstance(length, int):
            raise SchemaError(
                f"rule schema {rule.name!r}: the length {sequence.length!r} of "
                f"the sequence variable {sequence.argument!r} is not a natural "
                "number",
                sequence.line,
                sequence.col,
            )
        names: list[TypeName] = []
        for position in range(1, length + 1):
            variable = f"{sequence.argument}_{position}"
            if variable in used:
                raise SchemaError(
                    f"rule schema {rule.name!r}: the sequence variable "
                    f"{sequence.argument!r} stands for the name {variable!r}, "
                    "which the rule already uses; rename one of them",
                    sequence.line,
                    sequence.col,
                )
            names.append(TypeName(name=variable, line=sequence.line, col=sequence.col))
        return tuple(names)

    def substitute(pattern: ObjectExpr) -> ObjectExpr:
        if isinstance(pattern, TypeName):
            if pattern.name in environment:
                return pattern.with_(name=render_value(environment[pattern.name]))
            return pattern
        if isinstance(pattern, ObjectEffectApply):
            head = atom(
                pattern.effect, "the head of an application", pattern.line, pattern.col
            )
            for position, argument in enumerate(pattern.args):
                if isinstance(argument, ObjectSequence) and (
                    position != 0 or len(pattern.args) != 2
                ):
                    raise SchemaError(
                        f"rule schema {rule.name!r}: the name sequence "
                        f"`{argument.argument} ... {argument.length}` must be the "
                        f"first of two arguments, as `{pattern.effect}("
                        f"{argument.argument} ... {argument.length}, B)`, which "
                        f"applies {pattern.effect!r} once per name",
                        argument.line,
                        argument.col,
                    )
            first = pattern.args[0] if pattern.args else None
            if isinstance(first, ObjectSequence):
                result = substitute(pattern.args[1])
                for name in reversed(names_of(first)):
                    result = pattern.with_(effect=head, args=(name, result))
                return result
            return pattern.with_(
                effect=head,
                args=tuple(substitute(argument) for argument in pattern.args),
            )
        if isinstance(pattern, ObjectSpine):
            slash = atom(pattern.slash, "a slash", pattern.line, pattern.col)
            result = substitute(pattern.head)
            for name in names_of(pattern):
                result = ObjectEffectApply(
                    effect=slash,
                    args=(result, name),
                    line=pattern.line,
                    col=pattern.col,
                )
            return result
        if isinstance(pattern, ObjectSequence):
            raise SchemaError(
                f"rule schema {rule.name!r}: the name sequence "
                f"`{pattern.argument} ... {pattern.length}` stands for several "
                "names, so it is written only as the first argument of an "
                "application, as `Lam(z ... n, B)`",
                pattern.line,
                pattern.col,
            )
        return pattern

    options = tuple(
        _substitute_option(entry, environment, rule) for entry in rule.options
    )
    return SequentRule(
        name="_".join((rule.name, *(render_value(value) for value in assignment))),
        premises=tuple(substitute(premise) for premise in rule.premises),
        conclusion=substitute(rule.conclusion),
        options=options,
        line=rule.line,
        col=rule.col,
    )

shared_weight_key

shared_weight_key(rule: SequentRule) -> str | None

The weight-family index a rule's shared pragma reads, if any.

PARAMETER DESCRIPTION
rule

A rule with no parameters.

TYPE: SequentRule

RETURNS DESCRIPTION
str | None

F or F[a,b] (the family and its index, numerals as integers), or None for a rule without the pragma.

RAISES DESCRIPTION
SchemaError

If the pragma's value is not a family name or a family applied to numerals and names, or still names a parameter.

Source code in src/quivers/dsl/deduction_schemata.py
def shared_weight_key(rule: SequentRule) -> str | None:
    """The weight-family index a rule's ``shared`` pragma reads, if any.

    Parameters
    ----------
    rule : SequentRule
        A rule with no parameters.

    Returns
    -------
    str | None
        ``F`` or ``F[a,b]`` (the family and its index, numerals as
        integers), or ``None`` for a rule without the pragma.

    Raises
    ------
    SchemaError
        If the pragma's value is not a family name or a family applied to
        numerals and names, or still names a parameter.
    """
    for entry in rule.options:
        if entry.key != SHARED_OPTION:
            continue
        value = entry.value
        if isinstance(value, OptionName):
            return value.value
        if isinstance(value, OptionCall):
            rendered: list[str] = []
            parameters = {binder.name for binder in schema_parameters(rule)}
            for argument in value.args:
                if (
                    isinstance(argument, OptionName)
                    and argument.value not in parameters
                ):
                    rendered.append(argument.value)
                elif isinstance(argument, OptionNumber) and argument.value == int(
                    argument.value
                ):
                    rendered.append(str(int(argument.value)))
                else:
                    raise SchemaError(
                        f"rule {rule.name!r}: the shared weight family "
                        f"{value.func!r} is indexed by names and numerals",
                        entry.line or rule.line,
                        entry.col or rule.col,
                    )
            return f"{value.func}[{','.join(rendered)}]"
        raise SchemaError(
            f"rule {rule.name!r}: `shared` names a weight family, as `shared = F` "
            "or `shared = F(p, ...)`",
            entry.line or rule.line,
            entry.col or rule.col,
        )
    return None

family_parameter_key

family_parameter_key(key: str) -> str

The agenda engine's parameter key of a shared weight family's index.

PARAMETER DESCRIPTION
key

A shared_weight_key (F or F[a,b]).

TYPE: str

RETURNS DESCRIPTION
str

An injective spelling without dots: _ doubled, [ as _L, ] as _R, , as _C.

Source code in src/quivers/dsl/deduction_schemata.py
def family_parameter_key(key: str) -> str:
    """The agenda engine's parameter key of a shared weight family's index.

    Parameters
    ----------
    key : str
        A `shared_weight_key` (``F`` or ``F[a,b]``).

    Returns
    -------
    str
        An injective spelling without dots: ``_`` doubled, ``[`` as
        ``_L``, ``]`` as ``_R``, ``,`` as ``_C``.
    """
    return (
        key.replace("_", "__").replace("[", "_L").replace("]", "_R").replace(",", "_C")
    )

canonical_rule

canonical_rule(rule: SequentRule, atoms: frozenset[str]) -> str

A rule's premises and conclusion up to the names of its variables.

PARAMETER DESCRIPTION
rule

A rule.

TYPE: SequentRule

atoms

The deduction's atoms; every other identifier (not a numeral) of a pattern is a variable.

TYPE: frozenset[str]

RETURNS DESCRIPTION
str

The patterns with every variable renamed by first occurrence; two rules with equal renderings derive the same items.

Source code in src/quivers/dsl/deduction_schemata.py
def canonical_rule(rule: SequentRule, atoms: frozenset[str]) -> str:
    """A rule's premises and conclusion up to the names of its variables.

    Parameters
    ----------
    rule : SequentRule
        A rule.
    atoms : frozenset[str]
        The deduction's atoms; every other identifier (not a numeral) of a
        pattern is a variable.

    Returns
    -------
    str
        The patterns with every variable renamed by first occurrence; two
        rules with equal renderings derive the same items.
    """
    renaming: dict[str, str] = {}

    def render(pattern: ObjectExpr) -> str:
        if isinstance(pattern, TypeName):
            if pattern.name not in atoms and not pattern.name.isdigit():
                renaming.setdefault(pattern.name, f"_{len(renaming)}")
                return renaming[pattern.name]
            return pattern.name
        if isinstance(pattern, ObjectEffectApply):
            return (
                pattern.effect
                + "("
                + ", ".join(render(argument) for argument in pattern.args)
                + ")"
            )
        return type(pattern).__name__

    premises = ", ".join(render(premise) for premise in rule.premises)
    return f"{premises} |- {render(rule.conclusion)}"

deduction_reification

Item families of deduction signatures, inclusions, and copaired folds.

A deduction signature S that derives classes (deduction signature S deriving (Quote[Term via q])) has an item family of its own, S.Item, whose constructors are its atoms: the term algebra of the core. Every composed deduction G extending S then gets

  • the inclusion G.include.S : S.Item -> G.Item, the unique fold sending each core constructor to the constructor of G it is (its item family is Item[S | rho]: the core's constructors and the extension's);
  • every class S derives, derived for G.Item too. A class derived through morphisms (a fold, as Quote is) is copaired: G's own via morphisms, then the core's, each clause renamed from the constructor's declaring origin (S.Fwd, Lexicon.dog) to G's constructor (G.Fwd). The first clause for a constructor wins, so an extension may give a core constructor an algebra of its own; a constructor with no clause in any part is refused, naming the declaration that introduces it. There is no default clause.
  • the naturality law of each such fold along the inclusion, generated as a property: for every core item x, the core's fold of x equals the extension's fold of G.include.S(x), compared by the target's eq. The law fails exactly when an extension's own clause for a core constructor disagrees with the core's. It is a test of the module declaring the extension, so a flat program holds the laws of its root module's deductions only, titled with the names people write: quote of std.grammar.ccg.Categorial.Item is natural along its inclusion into G.Item, the extension identifying the instantiation.

Every generated declaration and refusal is located at the declaration it concerns: a core's fold where the signature derives it, and an extension's inclusion, copaired fold, and law where the deduction is declared, so a diagnostic names that declaration's file and line through the module graph's source map.

Binders take part like other constructors: a term's bound variables are items bound(k) numbered canonically in binding order, so the item term algebra is first-order, alpha-equivalent terms are equal items, and the inclusion, which keeps every number, preserves binding.

The slots S's rules leave open (slot_classes), and the slots of an atom its rules never apply, take the sorts each extension gives them, and a fold's clauses read each slot at one type, so the item family is instantiated once per sort assignment: S.Item when S leaves nothing open, else S.at_<sorts>.Item (CCGCore.at_int.Item for lexicalized extensions, CCGCore.at_item.Item for those taking axioms as input), each with its own constructors S.at_<sorts>.<atom> and its own derived classes. Each extension includes, and states the law along, its own instantiation; extensions with one assignment share one.

Composition identifies a constructor by its origin, so a clause may name it through any part reaching it, whatever the instantiation: its declaring signature (Categorial.S), any included signature extending that one (Reified.S for Reified extends Categorial), or the signature or deduction whose fold the clause is for. Every spelling is the one constructor, in the core's fold and in each extension's copair.

A core whose every constructor holds an item (Fwd, Bwd, and span with no atom) has no finite item, so its naturality law holds vacuously and is not generated.

Everything here is surface QVR generated from the composed deduction, so it elaborates and checks like hand-written code.

ReificationError

ReificationError(message: str, line: int, col: int)

Bases: ValueError

A signature whose item family or folds cannot be generated.

PARAMETER DESCRIPTION
message

What is wrong.

TYPE: str

line

Where.

TYPE: int

col

Where.

TYPE: int

Source code in src/quivers/dsl/deduction_reification.py
def __init__(self, message: str, line: int, col: int) -> None:
    super().__init__(message)
    self.line = line
    self.col = col

open_atoms

open_atoms(decl: DeductionDecl) -> frozenset[str]

The atoms a deduction signature's rules never mention.

Nothing in the signature fixes such an atom's arity or the sorts of its slots: each extension fixes them (_instantiation), and generic code over the signature requires what its own uses fix.

PARAMETER DESCRIPTION
decl

A deduction signature's atoms, binders, and rules, as a deduction with no lexicon.

TYPE: DeductionDecl

RETURNS DESCRIPTION
frozenset[str]

The atoms no rule writes, applied or bare.

Source code in src/quivers/dsl/deduction_reification.py
def open_atoms(decl: DeductionDecl) -> frozenset[str]:
    """The atoms a deduction signature's rules never mention.

    Nothing in the signature fixes such an atom's arity or the sorts of
    its slots: each extension fixes them (`_instantiation`), and generic
    code over the signature requires what its own uses fix.

    Parameters
    ----------
    decl : DeductionDecl
        A deduction signature's atoms, binders, and rules, as a deduction
        with no lexicon.

    Returns
    -------
    frozenset[str]
        The atoms no rule writes, applied or bare.
    """
    mentioned: set[str] = set()

    def visit(expr: ObjectExpr) -> None:
        if isinstance(expr, TypeName):
            mentioned.add(expr.name)
        symbol = pattern_symbol(expr)
        if symbol is None:
            return
        mentioned.add(symbol)
        for argument in pattern_arguments(expr):
            visit(argument)

    for rule in decl.rules:
        for pattern in (*rule.premises, rule.conclusion):
            visit(pattern)
    return frozenset(atom for atom in decl.atoms if atom not in mentioned)

slot_sorts

slot_sorts(decl: DeductionDecl) -> dict[str, tuple[str, ...]]

Each symbol of a deduction and the sorts of its slots.

A slot is Int where it holds a chart position (position_slots) or a bound variable's number, and an item otherwise. This is the item family the deduction's elaboration declares.

PARAMETER DESCRIPTION
decl

A composed deduction.

TYPE: DeductionDecl

RETURNS DESCRIPTION
dict[str, tuple[str, ...]]

"int" or "item" per slot, by symbol: atoms in declaration order, then binders, then the bound-variable item.

Source code in src/quivers/dsl/deduction_reification.py
def slot_sorts(decl: DeductionDecl) -> dict[str, tuple[str, ...]]:
    """Each symbol of a deduction and the sorts of its slots.

    A slot is ``Int`` where it holds a chart position (`position_slots`)
    or a bound variable's number, and an item otherwise. This is the item
    family the deduction's elaboration declares.

    Parameters
    ----------
    decl : DeductionDecl
        A composed deduction.

    Returns
    -------
    dict[str, tuple[str, ...]]
        ``"int"`` or ``"item"`` per slot, by symbol: atoms in declaration
        order, then binders, then the bound-variable item.
    """
    flags = position_slots(decl)
    sorts: dict[str, tuple[str, ...]] = {}
    for symbol, arity in _arities(decl).items():
        if symbol == BOUND_SYMBOL and decl.binders:
            sorts[symbol] = ("int",)
            continue
        marks = flags.get(symbol, [])
        sorts[symbol] = tuple(
            "int" if position < len(marks) and marks[position] else "item"
            for position in range(arity)
        )
    return sorts

slot_classes

slot_classes(decl: DeductionDecl) -> dict[str, tuple[str, ...]]

The slot sorts a deduction signature fixes, and those it leaves open.

A signature has no lexicon of its own, so whether a slot holds a chart position may be decided only by the deduction extending it: span's first two slots are positions in a deduction that reads a sentence through a lexicon and items in one that takes its axioms as input. A slot is

  • "int" when the signature's rules make it a position (a numeral fills it, or a variable shared with such a slot);
  • "item" when they fill it with an atom or an application (which no position slot holds), when it is a binder's bound variable, or when a variable connects it with such a slot;
  • "slot<k>" otherwise: one of the open classes, numbered in order of appearance, of slots the rules connect by shared variables. Every slot of a class has one sort in any deduction extending the signature, since a shared variable fills them all, and that sort is the extension's to fix.
PARAMETER DESCRIPTION
decl

A deduction signature's atoms, binders, and rules (schema instances included), as a deduction with no lexicon.

TYPE: DeductionDecl

RETURNS DESCRIPTION
dict[str, tuple[str, ...]]

The sort or class of each slot, by symbol, ordered as slot_sorts.

Source code in src/quivers/dsl/deduction_reification.py
def slot_classes(decl: DeductionDecl) -> dict[str, tuple[str, ...]]:
    """The slot sorts a deduction signature fixes, and those it leaves open.

    A signature has no lexicon of its own, so whether a slot holds a chart
    position may be decided only by the deduction extending it: ``span``'s
    first two slots are positions in a deduction that reads a sentence
    through a lexicon and items in one that takes its axioms as input. A
    slot is

    * ``"int"`` when the signature's rules make it a position (a numeral
      fills it, or a variable shared with such a slot);
    * ``"item"`` when they fill it with an atom or an application (which
      no position slot holds), when it is a binder's bound variable, or
      when a variable connects it with such a slot;
    * ``"slot<k>"`` otherwise: one of the open classes, numbered in order
      of appearance, of slots the rules connect by shared variables. Every
      slot of a class has one sort in any deduction extending the
      signature, since a shared variable fills them all, and that sort is
      the extension's to fix.

    Parameters
    ----------
    decl : DeductionDecl
        A deduction signature's atoms, binders, and rules (schema
        instances included), as a deduction with no lexicon.

    Returns
    -------
    dict[str, tuple[str, ...]]
        The sort or class of each slot, by symbol, ordered as `slot_sorts`.
    """
    arities = _arities(decl)
    flags = position_slots(decl)
    atoms = frozenset(decl.atoms) | frozenset(decl.binders)
    parent: dict[tuple[str, int], tuple[str, int]] = {}

    def find(slot: tuple[str, int]) -> tuple[str, int]:
        while parent.setdefault(slot, slot) != slot:
            slot = parent[slot]
        return slot

    def union(left: tuple[str, int], right: tuple[str, int]) -> None:
        parent[find(left)] = find(right)

    forced: dict[tuple[str, int], str] = {}
    for symbol, marks in flags.items():
        for position, positional in enumerate(marks):
            if positional:
                forced[(symbol, position)] = "int"
    for binder in decl.binders:
        if arities.get(binder, 0):
            forced.setdefault((binder, 0), "item")
    for rule in decl.rules:
        variables: dict[str, tuple[str, int]] = {}

        def visit(expr: ObjectExpr) -> None:
            symbol = pattern_symbol(expr)
            if symbol is None:
                return
            for position, argument in enumerate(pattern_arguments(expr)):
                slot = (symbol, position)
                find(slot)
                if isinstance(argument, TypeName) and argument.name not in atoms:
                    if argument.name.isdigit():
                        forced[slot] = "int"
                    elif argument.name in variables:
                        union(slot, variables[argument.name])
                    else:
                        variables[argument.name] = slot
                    continue
                forced.setdefault(slot, "item")
                visit(argument)

        for pattern in (*rule.premises, rule.conclusion):
            visit(pattern)
    decided: dict[tuple[str, int], str] = {}
    for slot, sort in forced.items():
        root = find(slot)
        if decided.get(root) != "int":
            decided[root] = sort
    classes: dict[tuple[str, int], str] = {}
    out: dict[str, tuple[str, ...]] = {}
    for symbol, arity in arities.items():
        if symbol == BOUND_SYMBOL and decl.binders:
            out[symbol] = ("int",)
            continue
        sorts: list[str] = []
        for position in range(arity):
            root = find((symbol, position))
            sort = decided.get(root)
            if sort is None:
                sort = classes.setdefault(root, f"slot{len(classes)}")
            sorts.append(sort)
        out[symbol] = tuple(sorts)
    return out

reify_cores

reify_cores(module: Module) -> Module

Generate the core families, inclusions, folds, and laws of a module.

PARAMETER DESCRIPTION
module

A module whose deductions are composed.

TYPE: Module

RETURNS DESCRIPTION
Module

The module itself when no extended signature derives a class; otherwise the module with each such signature's item family and its classes, each extension's inclusion and copaired classes, and the naturality law of each fold.

RAISES DESCRIPTION
ReificationError

If two extensions type a core constructor differently, or a fold names more than one target type.

Source code in src/quivers/dsl/deduction_reification.py
def reify_cores(module: Module) -> Module:
    """Generate the core families, inclusions, folds, and laws of a module.

    Parameters
    ----------
    module : Module
        A module whose deductions are composed.

    Returns
    -------
    Module
        The module itself when no extended signature derives a class;
        otherwise the module with each such signature's item family and
        its classes, each extension's inclusion and copaired classes, and
        the naturality law of each fold.

    Raises
    ------
    ReificationError
        If two extensions type a core constructor differently, or a fold
        names more than one target type.
    """
    if not any(
        isinstance(statement, DeductionDecl)
        and any(core.deriving for core in statement.cores)
        for statement in module.statements
    ):
        return module
    families: dict[str, tuple[QiecFamilyDecl, str]] = {}
    generated: list[Statement] = []
    laws: list[TestDecl] = []
    statements: list[Statement] = []
    for statement in module.statements:
        if not (
            isinstance(statement, DeductionDecl)
            and any(core.deriving for core in statement.cores)
        ):
            statements.append(statement)
            continue
        deduction = statement
        sorts = slot_sorts(deduction)
        origins = _origin_names(deduction)
        cores = {core.name for core in deduction.cores}
        introducing = {
            symbol: (
                f"deduction {source_spelling(origin)}"
                if origin == deduction.name
                else f"deduction signature {source_spelling(origin)}"
                if origin in cores
                else f"lexicon module {source_spelling(origin)}"
            )
            for symbol, origin in origins.items()
        }
        binders = frozenset(deduction.binders)
        # Each constructor's declaring parts; the bound-variable item
        # belongs to every part declaring a binder, and its description
        # names the first.
        declaring: dict[str, tuple[str, ...]] = {
            symbol: (origin,) for symbol, origin in origins.items()
        }
        if deduction.binders:
            binding = tuple(
                dict.fromkeys(origins[binder] for binder in deduction.binders)
            )
            declaring[BOUND_SYMBOL] = binding
            introducing[BOUND_SYMBOL] = introducing[deduction.binders[0]]
        own_constructors = {
            member_name(deduction.name, symbol): (
                f"{source_spelling(member_name(deduction.name, symbol))}, which "
                f"{description} introduces"
            )
            for symbol, description in introducing.items()
        }
        renaming = {
            spelled: member_name(deduction.name, symbol)
            for symbol, parts in declaring.items()
            for part in _paths(
                parts,
                deduction.name,
                tuple(
                    core.name
                    for core in deduction.cores
                    if _reaches(core, symbol, binders)
                ),
            )
            for spelled in _spellings(part, symbol)
        }
        derived = {_class_key(item): item for item in deduction.deriving}
        inherited: dict[str, list[str]] = {}
        prefixes: dict[str, str] = {}
        for core in reversed(deduction.cores):
            if not core.deriving:
                continue
            prefix = _instantiation(core, deduction, sorts)
            prefixes[core.name] = prefix
            family = _family(core, sorts, deduction, prefix)
            known = families.get(prefix)
            if known is not None and _shape(known[0]) != _shape(family):
                # One instantiation fixes the sort of every slot the core's
                # rules leave open; the others are fixed by those rules, so
                # an extension typing one otherwise is no extension of them.
                shown = source_spelling(core.name)
                raise ReificationError(
                    f"deductions {source_spelling(known[1])} and "
                    f"{source_spelling(deduction.name)} both extend {shown} and "
                    f"give its open slots the same sorts, but type a slot {shown}'s "
                    "rules fix differently",
                    deduction.line,
                    deduction.col,
                )
            if known is None:
                families[prefix] = (family, deduction.name)
                generated.append(family)
                below = tuple(
                    part for part in deduction.cores if part.name in core.includes
                )
                core_constructors = {
                    member_name(prefix, symbol): (
                        f"{source_spelling(member_name(core.name, symbol))}, which "
                        "deduction signature "
                        f"{source_spelling(declaring[symbol][0])} introduces"
                    )
                    for symbol in _core_constructors(core, deduction)
                }
                core_renaming = {
                    spelled: member_name(prefix, symbol)
                    for symbol in _core_constructors(core, deduction)
                    for spelled in (
                        *(
                            spelled
                            for part in _paths(
                                declaring[symbol],
                                core.name,
                                tuple(
                                    part.name
                                    for part in below
                                    if _reaches(part, symbol, binders)
                                ),
                            )
                            for spelled in _spellings(part, symbol)
                        ),
                        member_name(prefix, symbol),
                    )
                }
                core_classes: list[DerivingClass] = []
                for position, item in enumerate(core.deriving):
                    if not item.morphisms:
                        core_classes.append(item)
                        continue
                    algebra = _algebra(
                        item,
                        item.morphisms,
                        prefix,
                        core_renaming,
                        core_constructors,
                        _shown_family(core.name),
                        position,
                        deduction,
                    )
                    generated.extend(algebra)
                    head = algebra[0]
                    assert isinstance(head, MetaDecl)
                    core_classes.append(item.with_(morphisms=(head.declaration.name,)))
                # The core's fold concerns the signature, so it is derived,
                # and refused, where the signature derives it.
                generated.append(
                    DerivingDecl(
                        classes=tuple(core_classes),
                        family=member_name(prefix, "Item"),
                        shown=_shown_family(core.name),
                        line=core_classes[0].line if core_classes else deduction.line,
                        col=core_classes[0].col if core_classes else deduction.col,
                    )
                )
            generated.append(_inclusion(core, sorts, deduction, prefix))
            for item in core.deriving:
                inherited.setdefault(_class_key(item), []).extend(item.morphisms)
        classes: list[DerivingClass] = []
        for position, (key, morphisms) in enumerate(inherited.items()):
            own = derived.pop(key, None)
            # An inherited class is derived for the deduction's items, so it
            # is derived, and refused, where the deduction is declared.
            template = (
                own
                if own is not None
                else next(
                    item
                    for core in deduction.cores
                    for item in core.deriving
                    if _class_key(item) == key
                ).with_(line=deduction.line, col=deduction.col)
            )
            if not morphisms and (own is None or not own.morphisms):
                classes.append(template.with_(morphisms=()))
                continue
            parts = (*(own.morphisms if own is not None else ()), *morphisms)
            algebra = _algebra(
                template,
                parts,
                deduction.name,
                renaming,
                own_constructors,
                _shown_family(deduction.name),
                position,
                deduction,
            )
            generated.extend(algebra)
            first = algebra[0]
            assert isinstance(first, MetaDecl)
            classes.append(template.with_(morphisms=(first.declaration.name,)))
            if split_module(deduction.name)[0] is not None:
                # A flat program's tests are its root module's; an imported
                # deduction's laws are tests of the module declaring it.
                continue
            for core in deduction.cores:
                # A core whose every constructor holds an item has no finite
                # item at all, so its law holds vacuously and has no case to
                # test.
                if any(
                    _class_key(item) == key and item.morphisms for item in core.deriving
                ) and any(
                    "item" not in sorts.get(symbol, ())
                    for symbol in _core_constructors(core, deduction)
                ):
                    laws.append(
                        _naturality(template, core, deduction, prefixes[core.name])
                    )
        classes.extend(derived.values())
        statements.append(
            deduction.with_(
                deriving=tuple(classes),
                cores=tuple(core.with_(deriving=()) for core in deduction.cores),
            )
        )
    first = next(
        index
        for index, statement in enumerate(statements)
        if isinstance(statement, DeductionDecl) and statement.cores
    )
    statements[first + 1 : first + 1] = generated
    return module.with_(statements=tuple(statements), tests=(*module.tests, *laws))

deduction_conservativity

Classify the extension of a deduction signature by a deduction.

A deduction G extending a signature S may derive items that are already items of S's language (adding composition to an application core derives new S categories), so a result about the core need not survive the extension. In the vocabulary of theory inclusions (quivers.dsl.theories), the inclusion of S's rules into G's is

  • definitional when G adds no rules and no symbols to S;
  • conservative when, for every set of axioms in S's language, every item in S's language G derives from them S derives too;
  • neither when some axioms in S's language let G derive an S item S does not.

The checker establishes conservativity by a sufficient syntactic condition and refutes it with a witness, never by trust:

  • every rule G adds concludes an item whose pattern applies a symbol S lacks, so its conclusions are never S items, and every rule of G keeps every premise variable in its conclusion, so no rule turns an item mentioning such a symbol back into an S item: conservative;
  • a sentence over the entries of G's lexicon whose categories are in S's language, of at most MAX_LENGTH words, on which G's chart holds an S item that the chart of S's rules alone lacks: neither, with the sentence and the item as the witness;
  • anything else is undetermined.

Results of generic code typed against Deduction extends S hold for an extension exactly when its inclusion is conservative or definitional; extension_notes reports every other verdict so a reader knows a result about the core does not carry over.

MAX_LENGTH module-attribute

MAX_LENGTH = 3

The longest sentence a refutation search parses.

MAX_SENTENCES module-attribute

MAX_SENTENCES = 400

The most sentences a refutation search parses.

ExtensionVerdict didactic-model

ExtensionVerdict(*, deduction: str, signature: str, classification: Classification, reason: str, sentence: tuple[str, ...] = (), item: str = '', line: int = 0, col: int = 0)

Bases: Model

The classification of one deduction's extension of one signature.

PARAMETER DESCRIPTION
deduction

The extending deduction.

TYPE: str

signature

The extended signature.

TYPE: str

classification

What the checker established.

TYPE: Classification

reason

Why.

TYPE: str

sentence

For "neither", the sentence the witness parses.

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

item

For "neither", the item of the signature's language the extension derives on it and the signature's rules do not.

TYPE: str DEFAULT: ''

line

The deduction's location.

TYPE: int DEFAULT: 0

col

The deduction's location.

TYPE: int DEFAULT: 0

classify_extension

classify_extension(module: Module, deduction: DeductionDecl, signature: str) -> ExtensionVerdict

Classify a composed deduction's extension of one of its signatures.

PARAMETER DESCRIPTION
module

The composed module holding the deduction.

TYPE: Module

deduction

A composed deduction.

TYPE: DeductionDecl

signature

A signature it extends.

TYPE: str

RETURNS DESCRIPTION
ExtensionVerdict

The classification, with the reason or the witness.

Source code in src/quivers/dsl/deduction_conservativity.py
def classify_extension(
    module: Module, deduction: DeductionDecl, signature: str
) -> ExtensionVerdict:
    """Classify a composed deduction's extension of one of its signatures.

    Parameters
    ----------
    module : Module
        The composed module holding the deduction.
    deduction : DeductionDecl
        A composed deduction.
    signature : str
        A signature it extends.

    Returns
    -------
    ExtensionVerdict
        The classification, with the reason or the witness.
    """
    atoms = _core_atoms(deduction, signature)
    origins = _core_origins(deduction, signature)
    rule_origins = {origin.symbol: origin.origin for origin in deduction.rule_origins}
    core_rules = tuple(
        rule for rule in deduction.rules if rule_origins.get(rule.name) in origins
    )
    added = tuple(rule for rule in deduction.rules if rule not in core_rules)
    added_symbols = sorted(
        origin.symbol for origin in deduction.origins if origin.origin not in origins
    )
    base = ExtensionVerdict(
        deduction=deduction.name,
        signature=signature,
        classification="undetermined",
        reason="",
        line=deduction.line,
        col=deduction.col,
    )
    if not added and not added_symbols:
        return base.with_(
            classification="definitional",
            reason=f"{deduction.name} adds no rules and no symbols to {signature}",
        )
    if not added:
        return base.with_(
            classification="conservative",
            reason=(
                f"{deduction.name} adds symbols and no rules to {signature}, so "
                "from any axioms its rules derive what the signature's do"
            ),
        )
    all_atoms = frozenset(deduction.atoms)
    if all(_heads(rule.conclusion) - atoms for rule in added) and all(
        _keeps_variables(rule, all_atoms, position_slots(deduction))
        for rule in deduction.rules
    ):
        return base.with_(
            classification="conservative",
            reason=(
                f"every rule {deduction.name} adds concludes an item applying a "
                f"symbol {signature} lacks, and no rule forgets a premise variable"
            ),
        )
    words = tuple(
        dict.fromkeys(
            word
            for entry in deduction.lexicon
            if isinstance(entry.category, LexiconCategoryFixed)
            and _heads(entry.category.category) | _symbols(entry.category.category)
            <= atoms
            for word in entry.words
        )
    )
    if words:
        core = _system(module, deduction.with_(rules=core_rules, deriving=()))
        extended = _system(module, deduction.with_(deriving=()))
        for sentence in _sentences(words):
            known = {repr(item) for item, _ in core(list(sentence)).chart.items()}
            for item, weight in extended(list(sentence)).chart.items():
                if (
                    float(weight.detach()) != float("-inf")
                    and _in_language(item, atoms)
                    and repr(item) not in known
                ):
                    return base.with_(
                        classification="neither",
                        reason=(
                            f"on {' '.join(sentence)!r} the rules of "
                            f"{deduction.name} derive {item!r}, an item of "
                            f"{signature}'s language its own rules do not"
                        ),
                        sentence=sentence,
                        item=repr(item),
                    )
    return base.with_(
        reason=(
            f"no sufficient condition holds and no sentence of at most "
            f"{MAX_LENGTH} words over {signature}'s lexical entries refutes it"
        ),
    )

classify_extensions

classify_extensions(module: Module) -> tuple[ExtensionVerdict, ...]

Classify every extension of a signature by a deduction of a module.

PARAMETER DESCRIPTION
module

A module; its deductions are composed first.

TYPE: Module

RETURNS DESCRIPTION
tuple[ExtensionVerdict, ...]

One verdict per deduction and signature it extends, in order.

Source code in src/quivers/dsl/deduction_conservativity.py
def classify_extensions(module: Module) -> tuple[ExtensionVerdict, ...]:
    """Classify every extension of a signature by a deduction of a module.

    Parameters
    ----------
    module : Module
        A module; its deductions are composed first.

    Returns
    -------
    tuple[ExtensionVerdict, ...]
        One verdict per deduction and signature it extends, in order.
    """
    composed = compose_deductions(module)
    return tuple(
        classify_extension(composed, statement, core.name)
        for statement in composed.statements
        if isinstance(statement, DeductionDecl)
        for core in statement.cores
    )

extension_notes

extension_notes(module: Module) -> tuple[ExtensionVerdict, ...]

The extensions whose generic results do not carry over from the core.

PARAMETER DESCRIPTION
module

A module.

TYPE: Module

RETURNS DESCRIPTION
tuple[ExtensionVerdict, ...]

Every verdict that is neither definitional nor conservative: for those deductions, a result of generic code typed against Deduction extends S holds for S only.

Source code in src/quivers/dsl/deduction_conservativity.py
def extension_notes(module: Module) -> tuple[ExtensionVerdict, ...]:
    """The extensions whose generic results do not carry over from the core.

    Parameters
    ----------
    module : Module
        A module.

    Returns
    -------
    tuple[ExtensionVerdict, ...]
        Every verdict that is neither definitional nor conservative: for
        those deductions, a result of generic code typed against
        ``Deduction extends S`` holds for ``S`` only.
    """
    return tuple(
        verdict
        for verdict in classify_extensions(module)
        if verdict.classification not in ("definitional", "conservative")
    )

deduction_modules

Walk deduction bodies, deduction signatures, and lexicon modules.

A deduction and a deduction signature share one body language (atoms, binders, rules and rule schemata, rules instantiations, extends lines, lexicon blocks and lexicon references), so one walker reads it into a DeductionBody; each declaration then keeps the parts it admits. Rule patterns are walked by walk_rule_pattern, which is the only place a slash spine (Y |e Z ... n) is read: a spine anywhere else is not a pattern of a rule schema and quivers.dsl.parser.expressions refuses it.

EntryWalker

EntryWalker = Callable[[_Tree, str], LexiconEntry]

Walks one lexicon_entry vertex.

PragmaWalker

PragmaWalker = Callable[[_Tree, str | None], tuple[OptionEntry, ...]]

Walks a lexicon_pragma vertex (or its absence) into options.

DeductionBody didactic-model

DeductionBody(*, atoms: tuple[str, ...] = (), binders: tuple[str, ...] = (), rules: tuple[SequentRule, ...] = (), lexicon: tuple[LexiconEntry, ...] = (), lexicon_from_file: str | None = None, lexicon_from_file_options: tuple[OptionEntry, ...] = (), extends: tuple[DeductionExtension, ...] = (), lexicons: tuple[LexiconReference, ...] = (), instantiations: tuple[RuleInstantiation, ...] = (), lexicon_line: int = 0, lexicon_col: int = 0)

Bases: Model

The parts of one deduction or deduction-signature body.

PARAMETER DESCRIPTION
atoms

The declared atoms.

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

binders

The declared binder constructors.

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

rules

The rules and rule schemata.

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

lexicon

The entries of inline lexicon blocks.

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

lexicon_from_file

The path of a lexicon from line, if any.

TYPE: str | None DEFAULT: None

lexicon_from_file_options

That line's options.

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

extends

The extends entries.

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

lexicons

The lexicon modules named on lexicon lines.

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

instantiations

The rules entries.

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

lexicon_line

Where the first inline lexicon block or lexicon from line starts (line 0 when there is none), for refusing one in a signature.

TYPE: int DEFAULT: 0

lexicon_col

Where the first inline lexicon block or lexicon from line starts (line 0 when there is none), for refusing one in a signature.

TYPE: int DEFAULT: 0

walk_rule_pattern

walk_rule_pattern(t: _Tree, vid: str) -> ObjectExpr

Walk a premise or conclusion of a rule, reading slash spines.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

An object-expression vertex.

TYPE: str

RETURNS DESCRIPTION
ObjectExpr

The pattern; a spine becomes an ObjectSpine, and a name sequence an ObjectSequence.

RAISES DESCRIPTION
ParseError

If a spine is malformed.

Source code in src/quivers/dsl/parser/deduction_modules.py
def walk_rule_pattern(t: _Tree, vid: str) -> ObjectExpr:
    """Walk a premise or conclusion of a rule, reading slash spines.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        An object-expression vertex.

    Returns
    -------
    ObjectExpr
        The pattern; a spine becomes an `ObjectSpine`, and a name sequence
        an `ObjectSequence`.

    Raises
    ------
    ParseError
        If a spine is malformed.
    """
    kind = t.kind(vid)
    line, col = t.line_col(vid)
    if kind == "object_paren":
        return walk_rule_pattern(t, t.positional(vid)[0])
    if kind == "object_spine":
        head = t.field(vid, "head")
        if head is None:
            raise ParseError(f"object_spine missing head at {vid}")
        return ObjectSpine(
            head=walk_rule_pattern(t, head),
            slash=_required_text(t, t.field(vid, "slash"), vid, "slash"),
            argument=_required_text(t, t.field(vid, "argument"), vid, "argument"),
            length=_required_text(t, t.field(vid, "length"), vid, "length"),
            line=line,
            col=col,
        )
    if kind == "object_sequence":
        return ObjectSequence(
            argument=_required_text(t, t.field(vid, "argument"), vid, "argument"),
            length=_required_text(t, t.field(vid, "length"), vid, "length"),
            line=line,
            col=col,
        )
    if kind == "object_effect_apply":
        effect = _required_text(t, t.field(vid, "effect"), vid, "effect")
        return ObjectEffectApply(
            effect=effect,
            args=tuple(walk_rule_pattern(t, arg) for arg in t.fields(vid, "args")),
            line=line,
            col=col,
        )
    return _walk_type(t, vid)

walk_deduction_body

walk_deduction_body(t: _Tree, vid: str, *, entry: EntryWalker, pragma: PragmaWalker) -> DeductionBody

Walk the body entries of a deduction or a deduction signature.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The deduction_decl or deduction_signature_decl vertex.

TYPE: str

entry

Walks a lexicon entry.

TYPE: EntryWalker

pragma

Walks a rule's pragma.

TYPE: PragmaWalker

RETURNS DESCRIPTION
DeductionBody

Its parts, in source order.

RAISES DESCRIPTION
ParseError

If an entry is malformed.

Source code in src/quivers/dsl/parser/deduction_modules.py
def walk_deduction_body(
    t: _Tree, vid: str, *, entry: EntryWalker, pragma: PragmaWalker
) -> DeductionBody:
    """Walk the body entries of a deduction or a deduction signature.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``deduction_decl`` or ``deduction_signature_decl`` vertex.
    entry : EntryWalker
        Walks a lexicon entry.
    pragma : PragmaWalker
        Walks a rule's pragma.

    Returns
    -------
    DeductionBody
        Its parts, in source order.

    Raises
    ------
    ParseError
        If an entry is malformed.
    """
    atoms: list[str] = []
    binders: list[str] = []
    rules: list[SequentRule] = []
    lexicon: list[LexiconEntry] = []
    from_file: str | None = None
    from_file_options: tuple[OptionEntry, ...] = ()
    extends: list[DeductionExtension] = []
    lexicons: list[LexiconReference] = []
    instantiations: list[RuleInstantiation] = []
    lexicon_at: list[tuple[int, int]] = []
    for child in t.positional(vid):
        kind = t.kind(child)
        if kind == "deduction_atoms":
            atoms.extend(t.text(atom) for atom in t.fields(child, "atoms"))
        elif kind == "deduction_binders":
            binders.extend(t.text(binder) for binder in t.fields(child, "binders"))
        elif kind == "deduction_rule":
            rules.append(_walk_rule(t, child, pragma))
        elif kind == "deduction_lexicon":
            lexicon_at.append(t.line_col(child))
            lexicon.extend(
                entry(t, item)
                for item in t.positional(child)
                if t.kind(item) == "lexicon_entry"
            )
        elif kind == "deduction_lexicon_from_file":
            lexicon_at.append(t.line_col(child))
            path = _required_text(t, t.field(child, "path"), child, "path")
            if path.startswith('"') and path.endswith('"'):
                path = path[1:-1]
            from_file = path
            options = t.field(child, "options")
            from_file_options = _walk_option_block(t, options) if options else ()
        elif kind == "deduction_extends":
            for item in t.fields(child, "signatures"):
                line, col = t.line_col(item)
                extends.append(
                    DeductionExtension(
                        name=_required_text(t, t.field(item, "name"), item, "name"),
                        constraints=_walk_constraints(t, item),
                        weights=_weight_mode(t, item),
                        line=line,
                        col=col,
                    )
                )
        elif kind == "deduction_lexicon_modules":
            for item in t.fields(child, "lexicons"):
                line, col = t.line_col(item)
                lexicons.append(
                    LexiconReference(
                        name=_required_text(t, t.field(item, "name"), item, "name"),
                        weights=_weight_mode(t, item),
                        line=line,
                        col=col,
                    )
                )
        elif kind == "rule_instantiations":
            for item in t.fields(child, "instantiations"):
                line, col = t.line_col(item)
                condition = t.field(item, "condition")
                instantiations.append(
                    RuleInstantiation(
                        schema=_required_text(
                            t, t.field(item, "schema"), item, "schema"
                        ),
                        constraints=_walk_constraints(t, item),
                        condition=(
                            _walk_let_arith(t, condition)
                            if condition is not None
                            else None
                        ),
                        line=line,
                        col=col,
                    )
                )
    return DeductionBody(
        atoms=tuple(atoms),
        binders=tuple(binders),
        rules=tuple(rules),
        lexicon=tuple(lexicon),
        lexicon_from_file=from_file,
        lexicon_from_file_options=from_file_options,
        extends=tuple(extends),
        lexicons=tuple(lexicons),
        instantiations=tuple(instantiations),
        lexicon_line=lexicon_at[0][0] if lexicon_at else 0,
        lexicon_col=lexicon_at[0][1] if lexicon_at else 0,
    )

walk_deduction_signature_decl

walk_deduction_signature_decl(t: _Tree, vid: str, *, docs: tuple[str, ...], entry: EntryWalker, pragma: PragmaWalker) -> DeductionSignatureDecl

Walk a deduction signature declaration.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The deduction_signature_decl vertex.

TYPE: str

docs

Its doc comment.

TYPE: tuple[str, ...]

entry

Walks a lexicon entry.

TYPE: EntryWalker

pragma

Walks a rule's pragma.

TYPE: PragmaWalker

RETURNS DESCRIPTION
DeductionSignatureDecl

The signature.

RAISES DESCRIPTION
ParseError

If the body holds a lexicon block or a lexicon line: a signature has no lexicon, and lexical entries typed against it are a lexicon NAME for S module.

Source code in src/quivers/dsl/parser/deduction_modules.py
def walk_deduction_signature_decl(
    t: _Tree,
    vid: str,
    *,
    docs: tuple[str, ...],
    entry: EntryWalker,
    pragma: PragmaWalker,
) -> DeductionSignatureDecl:
    """Walk a ``deduction signature`` declaration.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``deduction_signature_decl`` vertex.
    docs : tuple[str, ...]
        Its doc comment.
    entry : EntryWalker
        Walks a lexicon entry.
    pragma : PragmaWalker
        Walks a rule's pragma.

    Returns
    -------
    DeductionSignatureDecl
        The signature.

    Raises
    ------
    ParseError
        If the body holds a lexicon block or a ``lexicon`` line: a
        signature has no lexicon, and lexical entries typed against it
        are a ``lexicon NAME for S`` module.
    """
    line, col = t.line_col(vid)
    name = _required_text(t, t.field(vid, "name"), vid, "name")
    body = walk_deduction_body(t, vid, entry=entry, pragma=pragma)
    if body.lexicon_line or body.lexicons:
        where = (
            (body.lexicon_line, body.lexicon_col)
            if body.lexicon_line
            else (body.lexicons[0].line, body.lexicons[0].col)
        )
        raise ParseError(
            f"line {where[0]}, col {where[1]}: deduction signature {name!r} declares "
            "no lexicon; write its entries in a lexicon module "
            f"`lexicon NAME for {name}` and take it with a `lexicon NAME` line of "
            "the deduction that extends the signature"
        )
    return DeductionSignatureDecl(
        name=name,
        extends=body.extends,
        atoms=body.atoms,
        binders=body.binders,
        rules=body.rules,
        instantiations=body.instantiations,
        docs=docs,
        line=line,
        col=col,
        deriving=walk_deriving_field(t, vid),
    )

walk_lexicon_decl

walk_lexicon_decl(t: _Tree, vid: str, *, docs: tuple[str, ...], entry: EntryWalker) -> LexiconDecl

Walk a lexicon NAME for S declaration.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The lexicon_decl vertex.

TYPE: str

docs

Its doc comment.

TYPE: tuple[str, ...]

entry

Walks a lexicon entry.

TYPE: EntryWalker

RETURNS DESCRIPTION
LexiconDecl

The lexicon module.

RAISES DESCRIPTION
ParseError

If its name or signature is missing.

Source code in src/quivers/dsl/parser/deduction_modules.py
def walk_lexicon_decl(
    t: _Tree, vid: str, *, docs: tuple[str, ...], entry: EntryWalker
) -> LexiconDecl:
    """Walk a ``lexicon NAME for S`` declaration.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``lexicon_decl`` vertex.
    docs : tuple[str, ...]
        Its doc comment.
    entry : EntryWalker
        Walks a lexicon entry.

    Returns
    -------
    LexiconDecl
        The lexicon module.

    Raises
    ------
    ParseError
        If its name or signature is missing.
    """
    line, col = t.line_col(vid)
    return LexiconDecl(
        name=_required_text(t, t.field(vid, "name"), vid, "name"),
        signature=_required_text(t, t.field(vid, "signature"), vid, "signature"),
        atoms=tuple(
            t.text(atom)
            for atoms in t.fields(vid, "atoms")
            for atom in t.fields(atoms, "atoms")
        ),
        entries=tuple(entry(t, item) for item in t.fields(vid, "entries")),
        docs=docs,
        line=line,
        col=col,
    )