Skip to content

Lexicon expansion

Category sets, polymorphic entries, synthesized meanings, templates, lexical rules, and refinements, expanded into ordinary deductions. The lexicon reference describes the surface, and the semantics states the rules.

lexical

Lexicon expansion: category sets, polymorphic entries, lexical rules, refinements.

A deduction may declare regular sets of categories (categories), the semantic type of each category (semantics), templates for families of entries, polymorphic entries whose categories quantify over category sets (∀ X in Conj. ...), lexical rules, atoms with features, and a base it refines. expand_lexical rewrites every such deduction into an ordinary one before any engine reads it, so the reference machine, the compiled runtime, and every transpile target see only atoms, rules, and monomorphic entries; meanings synthesized by meta computations are checked by the deduction's typing judgment, and a refinement is checked to restrict its base and given its forgetful map. A deduction with a lazily instantiated entry or a lexical rule in chart mode also gets an agenda plan (quivers.dsl.ast_nodes.plans), which the agenda engine runs in its place and reads back as the deduction before its items leave the engine.

  • quivers.dsl.lexical.terms: categories and meanings as first-order terms.
  • quivers.dsl.lexical.categories: category sets.
  • quivers.dsl.lexical.universe: the categories a grammar attests.
  • quivers.dsl.lexical.semantics: semantic types and the typing check.
  • quivers.dsl.lexical.synthesis: meanings synthesized by meta computations.
  • quivers.dsl.lexical.entries: templates and polymorphic entries.
  • quivers.dsl.lexical.lexical_rules: lexical rules.
  • quivers.dsl.lexical.lazy: lazy instantiation by rule specialization.
  • quivers.dsl.lexical.features: atoms with features.
  • quivers.dsl.lexical.refinement: refinements and their forgetful maps.
  • quivers.dsl.lexical.expand: the expansion of a module.

ENTRY_OPTIONS module-attribute

ENTRY_OPTIONS = frozenset({'learnable', 'shared', 'bound', 'instantiate', 'per_instance'})

The options a lexicon entry or a template may carry.

OPERATION_OPTIONS module-attribute

OPERATION_OPTIONS = frozenset({'guard', 'weight'})

Rule options naming a computation over the rule's matched variables, which a specialized rule reads from its source rather than carrying.

LEVEL module-attribute

LEVEL = '__lexical_level'

The prefix of the atoms counting the chart rule applications behind a lexical item.

LIFT module-attribute

LIFT = '__lexical_lift'

The generated rule that unwraps a lexical item.

MODES module-attribute

MODES = ('compile', 'chart')

Where a lexical rule is applied.

WRAPPER module-attribute

WRAPPER = '__lexical_item'

The atom wrapping a lexical item's category when lexical rules run in the chart.

SPAN_HEAD module-attribute

SPAN_HEAD = 'span'

The head of the items a lexicon yields: span(i, j, category[, meaning]).

CategorySets

CategorySets(declarations: Iterable[CategorySetDecl], is_atom: Callable[[str], bool], owner: str)

The category sets of one deduction.

PARAMETER DESCRIPTION
declarations

The categories lines.

TYPE: Iterable[CategorySetDecl]

is_atom

Whether a name is one of the deduction's atoms.

TYPE: Callable[[str], bool]

owner

The deduction, for diagnostics.

TYPE: str

RAISES DESCRIPTION
LexicalError

If two sets share a name, a set is named like an atom, a member names something that is neither an atom nor a set, or a set is a member of itself without a constructor in between (so membership would not be decided by recursion on terms).

Source code in src/quivers/dsl/lexical/categories.py
def __init__(
    self,
    declarations: Iterable[CategorySetDecl],
    is_atom: Callable[[str], bool],
    owner: str,
) -> None:
    self.owner = owner
    decls = tuple(declarations)
    self.declarations: dict[str, CategorySetDecl] = {}
    for decl in decls:
        if decl.name in self.declarations:
            raise LexicalError(
                f"{owner}: category set {decl.name!r} is declared twice",
                decl.line,
                decl.col,
            )
        if is_atom(decl.name):
            raise LexicalError(
                f"{owner}: category set {decl.name!r} is named like an atom",
                decl.line,
                decl.col,
            )
        self.declarations[decl.name] = decl
    names = frozenset(self.declarations)
    self.members: dict[str, tuple[Term, ...]] = {}
    for decl in decls:
        members: list[Term] = []
        for expr in decl.members:
            term = from_object(
                expr,
                lambda name: is_atom(name) or name in names,
                owner=f"{owner}: category set {decl.name!r}",
            )
            stray = [
                variable
                for variable in _variables(term)
                if variable not in names and not is_atom(variable)
            ]
            if stray:
                raise LexicalError(
                    f"{owner}: category set {decl.name!r} names "
                    f"{stray[0]!r}, which is neither an atom nor a category set",
                    decl.line,
                    decl.col,
                )
            members.append(term)
        self.members[decl.name] = tuple(members)
    self._check_productive()
    self._memo: dict[tuple[str, Term], bool] = {}

finite cached property

finite: frozenset[str]

The sets no set reaches itself from: the finite ones.

RETURNS DESCRIPTION
frozenset[str]

Their names.

__contains__

__contains__(name: str) -> bool

Whether a set of that name is declared.

PARAMETER DESCRIPTION
name

The name.

TYPE: str

RETURNS DESCRIPTION
bool

Whether it names a set.

Source code in src/quivers/dsl/lexical/categories.py
def __contains__(self, name: str) -> bool:
    """Whether a set of that name is declared.

    Parameters
    ----------
    name : str
        The name.

    Returns
    -------
    bool
        Whether it names a set.
    """
    return name in self.declarations

require

require(name: str, line: int, col: int) -> None

Refuse a name that is no declared set.

PARAMETER DESCRIPTION
name

The name.

TYPE: str

line

Where it is used.

TYPE: int

col

Where it is used.

TYPE: int

RAISES DESCRIPTION
LexicalError

If no category set has that name.

Source code in src/quivers/dsl/lexical/categories.py
def require(self, name: str, line: int, col: int) -> None:
    """Refuse a name that is no declared set.

    Parameters
    ----------
    name : str
        The name.
    line : int
        Where it is used.
    col : int
        Where it is used.

    Raises
    ------
    LexicalError
        If no category set has that name.
    """
    if name not in self.members:
        declared = ", ".join(sorted(self.members)) or "none"
        raise LexicalError(
            f"{self.owner}: {name!r} is not a declared category set "
            f"(declared: {declared})",
            line,
            col,
        )

contains

contains(name: str, term: Term) -> bool

Whether a ground term belongs to a set.

PARAMETER DESCRIPTION
name

The set.

TYPE: str

term

The term.

TYPE: Term

RETURNS DESCRIPTION
bool

Membership.

Source code in src/quivers/dsl/lexical/categories.py
def contains(self, name: str, term: Term) -> bool:
    """Whether a ground term belongs to a set.

    Parameters
    ----------
    name : str
        The set.
    term : Term
        The term.

    Returns
    -------
    bool
        Membership.
    """
    key = (name, term)
    cached = self._memo.get(key)
    if cached is not None:
        return cached
    result = any(self._matches(member, term) for member in self.members[name])
    self._memo[key] = result
    return result

enumerate

enumerate(name: str) -> tuple[Term, ...]

Every member of a finite set, in declaration order.

PARAMETER DESCRIPTION
name

The set.

TYPE: str

RETURNS DESCRIPTION
tuple[Term, ...]

Its members, each once.

RAISES DESCRIPTION
LexicalError

If the set is infinite.

Source code in src/quivers/dsl/lexical/categories.py
def enumerate(self, name: str) -> tuple[Term, ...]:
    """Every member of a finite set, in declaration order.

    Parameters
    ----------
    name : str
        The set.

    Returns
    -------
    tuple[Term, ...]
        Its members, each once.

    Raises
    ------
    LexicalError
        If the set is infinite.
    """
    if name not in self.finite:
        decl = self.declarations[name]
        raise LexicalError(
            f"{self.owner}: category set {name!r} contains itself under a "
            "constructor, so it is infinite and has no list of members",
            decl.line,
            decl.col,
        )
    found: dict[Term, None] = {}
    for member in self.members[name]:
        for term in self._expand(member):
            found.setdefault(term, None)
    return tuple(found)

describe

describe(name: str) -> str

Spell a set's declaration.

PARAMETER DESCRIPTION
name

The set.

TYPE: str

RETURNS DESCRIPTION
str

Name = m1, m2, ....

Source code in src/quivers/dsl/lexical/categories.py
def describe(self, name: str) -> str:
    """Spell a set's declaration.

    Parameters
    ----------
    name : str
        The set.

    Returns
    -------
    str
        ``Name = m1, m2, ...``.
    """
    return f"{name} = " + ", ".join(render(m) for m in self.members[name])

Instance didactic-model

Instance(*, word: str, category: Term, meaning: LetExprNode, learnable: bool = False, weights: tuple[str, ...] = (), apart: bool = False, source: int = 0, lazy: bool = False, line: int = 0, col: int = 0)

Bases: Model

One monomorphic lexicon entry.

PARAMETER DESCRIPTION
word

The word.

TYPE: str

category

The ground category.

TYPE: Term

meaning

The meaning.

TYPE: LetExprNode

learnable

Whether the instance has a learned weight of its own.

TYPE: bool DEFAULT: False

weights

The weight families it reads.

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

apart

Whether its entry weighs each instance apart (per_instance): its weight family is the entry's family at its instantiation.

TYPE: bool DEFAULT: False

source

The index of the written entry it comes from.

TYPE: int DEFAULT: 0

lazy

Whether its entry is instantiated lazily.

TYPE: bool DEFAULT: False

line

The written entry's line.

TYPE: int DEFAULT: 0

col

The written entry's column.

TYPE: int DEFAULT: 0

entry

entry() -> LexiconEntry

The instance as a plain lexicon entry.

RETURNS DESCRIPTION
LexiconEntry

The entry, with no option but learnable.

RAISES DESCRIPTION
LexicalError

If the category cannot be written as a category.

Source code in src/quivers/dsl/lexical/entries.py
def entry(self) -> LexiconEntry:
    """The instance as a plain lexicon entry.

    Returns
    -------
    LexiconEntry
        The entry, with no option but ``learnable``.

    Raises
    ------
    LexicalError
        If the category cannot be written as a category.
    """
    return LexiconEntry(
        words=(self.word,),
        category=LexiconCategoryFixed(
            category=to_object(self.category, self.line, self.col)
        ),
        lf=self.meaning,
        options=(
            (OptionEntry(key="learnable", value=OptionFlag()),)
            if self.learnable
            else ()
        ),
        line=self.line,
        col=self.col,
        weights=self.weights,
    )

Schema didactic-model

Schema(*, words: tuple[str, ...], binders: tuple[CategoryBinder, ...], category: Term, meaning: LetExprNode, options: tuple[OptionEntry, ...] = (), index: int = 0, line: int = 0, col: int = 0)

Bases: Model

A written entry read as a schema: binders, category, meaning, options.

PARAMETER DESCRIPTION
words

Its words.

TYPE: tuple[str, ...]

binders

Its category variables and their sets.

TYPE: tuple[CategoryBinder, ...]

category

Its category, over the variables.

TYPE: Term

meaning

Its meaning.

TYPE: LetExprNode

options

Its options, template options first.

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

index

Its position in the lexicon.

TYPE: int DEFAULT: 0

line

Its line.

TYPE: int DEFAULT: 0

col

Its column.

TYPE: int DEFAULT: 0

LexicalError

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

Bases: ValueError

A deduction's lexicon, category sets, or refinement cannot be expanded.

PARAMETER DESCRIPTION
message

What is wrong, naming the declaration and the property it lacks.

TYPE: str

line

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

TYPE: int DEFAULT: 0

col

The 0-based source column, or 0 when unknown.

TYPE: int DEFAULT: 0

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

code class-attribute instance-attribute

code = 'qiec-lexicon'

The diagnostic code every lexicon refusal carries.

LexicalExpansion didactic-model

LexicalExpansion(*, module: Module = field(opaque=True, extras=OPAQUE_BY_VALUE), refinements: Mapping[str, Refinement] = field(opaque=True, default_factory=dict, extras=OPAQUE_BY_VALUE), plans: Mapping[str, AgendaPlan] = field(opaque=True, default_factory=dict, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A module with plain deductions, the refinements it declares, and agenda plans.

PARAMETER DESCRIPTION
module

The module.

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

refinements

The forgetful map of each refined deduction, by name.

TYPE: Mapping[str, Refinement] DEFAULT: field(opaque=True, default_factory=dict, extras=OPAQUE_BY_VALUE)

plans

The deduction the agenda engine runs in place of each deduction with a lazily instantiated entry or a lexical rule in chart mode, by name.

TYPE: Mapping[str, AgendaPlan] DEFAULT: field(opaque=True, default_factory=dict, extras=OPAQUE_BY_VALUE)

Features didactic-model

Features(*, sets: Mapping[str, tuple[str, ...]] = field(opaque=True, extras=OPAQUE_BY_VALUE), values: Mapping[str, tuple[tuple[str, ...], ...]] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The featured atoms of one deduction.

PARAMETER DESCRIPTION
sets

Each featured atom's feature sets, in order.

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

values

Each featured atom's admissible values at each feature.

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

atoms property

atoms: frozenset[str]

The featured atoms.

RETURNS DESCRIPTION
frozenset[str]

Their names.

instances

instances() -> dict[str, str]

Every atom the featured atoms stand for, with the atom it refines.

RETURNS DESCRIPTION
dict[str, str]

NP__sg to NP, for each assignment.

Source code in src/quivers/dsl/lexical/features.py
def instances(self) -> dict[str, str]:
    """Every atom the featured atoms stand for, with the atom it refines.

    Returns
    -------
    dict[str, str]
        ``NP__sg`` to ``NP``, for each assignment.
    """
    found: dict[str, str] = {}
    for atom, choices in self.values.items():
        for assignment in product(*choices):
            found[featured_name(atom, assignment)] = atom
    return found

ground

ground(term: Term, where: str, line: int, col: int) -> Term

Replace every featured atom of a ground term by its atom.

PARAMETER DESCRIPTION
term

A category or item.

TYPE: Term

where

Its owner, for diagnostics.

TYPE: str

line

Where it is written.

TYPE: int

col

Where it is written.

TYPE: int

RETURNS DESCRIPTION
Term

The term over plain atoms.

RAISES DESCRIPTION
LexicalError

If a featured atom is written bare, with the wrong number of features, or with a value outside its feature's set.

Source code in src/quivers/dsl/lexical/features.py
def ground(self, term: Term, where: str, line: int, col: int) -> Term:
    """Replace every featured atom of a ground term by its atom.

    Parameters
    ----------
    term : Term
        A category or item.
    where : str
        Its owner, for diagnostics.
    line : int
        Where it is written.
    col : int
        Where it is written.

    Returns
    -------
    Term
        The term over plain atoms.

    Raises
    ------
    LexicalError
        If a featured atom is written bare, with the wrong number of
        features, or with a value outside its feature's set.
    """
    if isinstance(term, Variable):
        return term
    assert isinstance(term, Node)
    if term.form == "features":
        if term.head not in self.sets:
            raise LexicalError(
                f"{where}: {term.head!r} is written with features, which its "
                "atoms line does not declare",
                line,
                col,
            )
        choices = self.values[term.head]
        if len(term.args) != len(choices):
            raise LexicalError(
                f"{where}: {term.head} takes {len(choices)} features, not "
                f"{len(term.args)}",
                line,
                col,
            )
        values: list[str] = []
        for value, allowed, set_name in zip(
            term.args, choices, self.sets[term.head], strict=True
        ):
            if (
                not isinstance(value, Node)
                or value.args
                or value.head not in allowed
            ):
                raise LexicalError(
                    f"{where}: {render(value)} is no member of {set_name}, the "
                    f"set of a feature of {term.head}",
                    line,
                    col,
                )
            values.append(value.head)
        return Node(head=featured_name(term.head, values))
    if not term.args and term.form == "atom" and term.head in self.sets:
        raise LexicalError(
            f"{where}: {term.head} has features, so it is written {term.head}[...]",
            line,
            col,
        )
    if not term.args:
        return term
    return term.with_(
        args=tuple(self.ground(a, where, line, col) for a in term.args)
    )

variables

variables(term: Term) -> dict[str, frozenset[str]]

The feature variables of a term and the values each may take.

PARAMETER DESCRIPTION
term

A rule's premise or conclusion.

TYPE: Term

RETURNS DESCRIPTION
dict[str, frozenset[str]]

Each variable filling a feature, with the values of every feature it fills.

Source code in src/quivers/dsl/lexical/features.py
def variables(self, term: Term) -> dict[str, frozenset[str]]:
    """The feature variables of a term and the values each may take.

    Parameters
    ----------
    term : Term
        A rule's premise or conclusion.

    Returns
    -------
    dict[str, frozenset[str]]
        Each variable filling a feature, with the values of every
        feature it fills.
    """
    found: dict[str, frozenset[str]] = {}

    def visit(t: Term) -> None:
        if not isinstance(t, Node):
            return
        if t.form == "features" and t.head in self.values:
            for value, allowed in zip(t.args, self.values[t.head], strict=False):
                if isinstance(value, Variable):
                    found[value.name] = found.get(
                        value.name, frozenset(allowed)
                    ) & frozenset(allowed)
        for a in t.args:
            visit(a)

    visit(term)
    return found

Specialization didactic-model

Specialization(*, placeholders: tuple[Instance, ...] = (), rules: tuple[SequentRule, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), instances: Mapping[str, Mapping[int, Term]] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), names: tuple[str, ...] = (), consumed: Mapping[str, tuple[tuple[str, str, Term], ...]] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

What lazy instantiation adds to a deduction.

PARAMETER DESCRIPTION
placeholders

One entry per word and meaning of each lazy entry, its category the placeholder atom and its meaning the instances' meaning.

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

rules

The specialized rules.

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

instances

Each specialized rule's instance category at each position that takes a placeholder, for reading a derivation back as one over the instances.

TYPE: Mapping[str, Mapping[int, Term]] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE)

names

The placeholder atom of each lazy instance, in the order given.

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

consumed

Each specialized rule's consumed instances, in premise order: the placeholder, the word, and the instance category.

TYPE: Mapping[str, tuple[tuple[str, str, Term], ...]] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE)

ReadRule

ReadRule(rule: LexicalRuleDecl, is_atom: Callable[[str], bool], owner: str)

A lexical rule read as terms.

PARAMETER DESCRIPTION
rule

The rule.

TYPE: LexicalRuleDecl

is_atom

Whether a name is an atom.

TYPE: Callable[[str], bool]

owner

The deduction, for diagnostics.

TYPE: str

RAISES DESCRIPTION
LexicalError

If an option is unknown or malformed, an item is not a span, the premise's positions are not variables, or the conclusion's span is not the premise's.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def __init__(
    self, rule: LexicalRuleDecl, is_atom: Callable[[str], bool], owner: str
) -> None:
    self.rule = rule
    where = f"{owner}: lexical rule {rule.name!r}"
    self.where = where
    self.learnable = False
    self.mode = "compile"
    self.bound = 1
    for option in rule.options:
        if option.key not in RULE_OPTIONS:
            raise LexicalError(
                f"{where}: unknown option {option.key!r} (a lexical rule takes "
                f"{', '.join(sorted(RULE_OPTIONS))})",
                option.line or rule.line,
                option.col or rule.col,
            )
        if option.key == "learnable":
            self.learnable = True
        elif option.key == "mode":
            if (
                not isinstance(option.value, OptionName)
                or option.value.value not in MODES
            ):
                raise LexicalError(
                    f"{where}: mode is {' or '.join(MODES)}",
                    option.line or rule.line,
                    option.col or rule.col,
                )
            self.mode = option.value.value
        else:
            value = option.value
            if (
                not isinstance(value, OptionNumber)
                or not float(value.value).is_integer()
                or value.value < 1
            ):
                raise LexicalError(
                    f"{where}: bound takes a positive integer",
                    option.line or rule.line,
                    option.col or rule.col,
                )
            self.bound = int(value.value)
    self.premise = from_object(rule.premise, is_atom, owner=where)
    self.conclusion = from_object(rule.conclusion, is_atom, owner=where)
    for item in (self.premise, self.conclusion):
        if (
            not isinstance(item, Node)
            or item.head != SPAN_HEAD
            or len(item.args) not in (3, 4)
        ):
            raise LexicalError(
                f"{where}: relates two lexical items, span(i, j, category"
                f"[, meaning]), not {render(item)}",
                rule.line,
                rule.col,
            )
    assert isinstance(self.premise, Node) and isinstance(self.conclusion, Node)
    if len(self.premise.args) != len(self.conclusion.args):
        raise LexicalError(
            f"{where}: its premise and conclusion have different shapes",
            rule.line,
            rule.col,
        )
    start, stop = self.premise.args[0], self.premise.args[1]
    if not isinstance(start, Variable) or not isinstance(stop, Variable):
        raise LexicalError(
            f"{where}: its premise's positions are variables", rule.line, rule.col
        )
    if self.conclusion.args[:2] != (start, stop):
        raise LexicalError(
            f"{where}: keeps its item's span, so its conclusion's positions are "
            f"{start.name} and {stop.name}",
            rule.line,
            rule.col,
        )
    self.forms = len(self.premise.args) == 4

family property

family: tuple[str, ...]

The weight family the rule contributes, when it learns one.

RETURNS DESCRIPTION
tuple[str, ...]

(__lexical_rule_<r>,) or empty.

apply

apply(instance: Instance) -> Instance | None

The entry the rule derives from one entry, if its premise matches.

PARAMETER DESCRIPTION
instance

The entry.

TYPE: Instance

RETURNS DESCRIPTION
Instance | None

The derived entry, reading the entry's weights and the rule's.

RAISES DESCRIPTION
LexicalError

If the conclusion's category is not ground.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def apply(self, instance: Instance) -> Instance | None:
    """The entry the rule derives from one entry, if its premise matches.

    Parameters
    ----------
    instance : Instance
        The entry.

    Returns
    -------
    Instance | None
        The derived entry, reading the entry's weights and the rule's.

    Raises
    ------
    LexicalError
        If the conclusion's category is not ground.
    """
    assert isinstance(self.premise, Node) and isinstance(self.conclusion, Node)
    slots: list[Term] = [
        Variable(name="__start"),
        Variable(name="__stop"),
        instance.category,
    ]
    if self.forms:
        slots.append(from_meaning(instance.meaning, owner=self.where))
    bindings = match(
        self.premise, Node(head=SPAN_HEAD, args=tuple(slots), form="apply")
    )
    if bindings is None:
        return None
    category = substitute(self.conclusion.args[2], bindings)
    if variables_of(category):
        raise LexicalError(
            f"{self.where}: concludes with {render(category)}, whose "
            f"{variables_of(category)[0]} no premise binds",
            self.rule.line,
            self.rule.col,
        )
    meaning = instance.meaning
    if self.forms:
        meaning = to_meaning(
            substitute(self.conclusion.args[3], bindings),
            instance.line,
            instance.col,
        )
    return Instance(
        word=instance.word,
        category=category,
        meaning=meaning,
        learnable=False,
        weights=(*instance.weights, *self.family),
        source=instance.source,
        lazy=False,
        line=instance.line,
        col=instance.col,
    )

Derivation didactic-model

Derivation(*, item: Hashable = field(opaque=True, extras=OPAQUE_BY_IDENTITY), rule: str = '', premises: tuple[Derivation, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A derivation read off a chart: an item, its rule, its premises.

PARAMETER DESCRIPTION
item

The item derived, in the chart's representation. It may be any hashable host value and is compared by identity.

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

rule

The rule applied, or empty for a lexical axiom.

TYPE: str DEFAULT: ''

premises

The derivations of its premises, in order.

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

Refinement didactic-model

Refinement(*, name: str, base: str, atom_images: Mapping[str, str] = field(opaque=True, extras=OPAQUE_BY_VALUE), rule_images: Mapping[str, str] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The forgetful map of one refinement.

PARAMETER DESCRIPTION
name

The refined deduction.

TYPE: str

base

The deduction it refines.

TYPE: str

atom_images

Each atom of the refinement that is not one of the base's, with the base atom it forgets to.

TYPE: Mapping[str, str] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

rule_images

Each rule of the refinement with the base rule it maps to.

TYPE: Mapping[str, str] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

forget

forget(term: Term) -> Term

The forgetful image of a category, item, or rule pattern.

PARAMETER DESCRIPTION
term

A term of the refinement.

TYPE: Term

RETURNS DESCRIPTION
Term

The base term.

Source code in src/quivers/dsl/lexical/refinement.py
def forget(self, term: Term) -> Term:
    """The forgetful image of a category, item, or rule pattern.

    Parameters
    ----------
    term : Term
        A term of the refinement.

    Returns
    -------
    Term
        The base term.
    """
    if isinstance(term, Variable):
        return term
    assert isinstance(term, Node)
    head = self.atom_images.get(term.head, term.head)
    if not term.args:
        return term if head == term.head else Node(head=head)
    return term.with_(head=head, args=tuple(self.forget(a) for a in term.args))

forget_item

forget_item(item: Hashable) -> Hashable

The forgetful image of a chart item, as the agenda engine holds it.

PARAMETER DESCRIPTION
item

A refined item: a tuple whose atoms are ("atom", name).

TYPE: Hashable

RETURNS DESCRIPTION
Hashable

The base item.

Source code in src/quivers/dsl/lexical/refinement.py
def forget_item(self, item: Hashable) -> Hashable:
    """The forgetful image of a chart item, as the agenda engine holds it.

    Parameters
    ----------
    item : Hashable
        A refined item: a tuple whose atoms are ``("atom", name)``.

    Returns
    -------
    Hashable
        The base item.
    """
    if not isinstance(item, tuple) or not item:
        return item
    if len(item) == 2 and item[0] == "atom" and isinstance(item[1], str):
        return ("atom", self.atom_images.get(item[1], item[1]))
    head = item[0]
    if isinstance(head, str):
        head = self.atom_images.get(head, head)
    return (head, *(self.forget_item(part) for part in item[1:]))

forget_derivation

forget_derivation(derivation: Derivation) -> Derivation

The forgetful image of a derivation.

PARAMETER DESCRIPTION
derivation

A derivation in the refined deduction's chart.

TYPE: Derivation

RETURNS DESCRIPTION
Derivation

Its image: every item forgotten, every rule its base rule.

RAISES DESCRIPTION
LexicalError

If the derivation applies a rule the refinement does not have.

Source code in src/quivers/dsl/lexical/refinement.py
def forget_derivation(self, derivation: Derivation) -> Derivation:
    """The forgetful image of a derivation.

    Parameters
    ----------
    derivation : Derivation
        A derivation in the refined deduction's chart.

    Returns
    -------
    Derivation
        Its image: every item forgotten, every rule its base rule.

    Raises
    ------
    LexicalError
        If the derivation applies a rule the refinement does not have.
    """
    rule = derivation.rule
    if rule:
        if rule not in self.rule_images:
            raise LexicalError(
                f"deduction {self.name!r} has no rule {rule!r} to forget"
            )
        rule = self.rule_images[rule]
    return Derivation(
        item=self.forget_item(derivation.item),
        rule=rule,
        premises=tuple(self.forget_derivation(p) for p in derivation.premises),
    )

SemanticTypes

SemanticTypes(declaration: SemanticsDecl, is_atom: Callable[[str], bool], judgments: Mapping[str, JudgmentSystem], owner: str)

The semantic types of one deduction's categories.

PARAMETER DESCRIPTION
declaration

The semantics block.

TYPE: SemanticsDecl

is_atom

Whether a name is one of the deduction's atoms.

TYPE: Callable[[str], bool]

judgments

The module's judgments.

TYPE: Mapping[str, JudgmentSystem]

owner

The deduction, for diagnostics.

TYPE: str

RAISES DESCRIPTION
LexicalError

If the judgment is undeclared or is not Ty(ctx, term, type).

Source code in src/quivers/dsl/lexical/semantics.py
def __init__(
    self,
    declaration: SemanticsDecl,
    is_atom: Callable[[str], bool],
    judgments: Mapping[str, JudgmentSystem],
    owner: str,
) -> None:
    self.declaration = declaration
    self.owner = owner
    system = judgments.get(declaration.judgment)
    if system is None:
        raise LexicalError(
            f"{owner}: semantics names {declaration.judgment!r}, which is not a "
            "declared judgment",
            declaration.line,
            declaration.col,
        )
    form = system.forms[declaration.judgment]
    contexts = [a for a in form.arguments if a.context]
    if len(form.arguments) != 3 or len(contexts) != 1:
        raise LexicalError(
            f"{owner}: semantics checks meanings with "
            f"{declaration.judgment!r} as Ty(ctx, term, type)",
            declaration.line,
            declaration.col,
        )
    self.system = system
    self.clauses: list[tuple[Term, Term, surface.ObjectExpr]] = []
    for clause in declaration.clauses:
        pattern = from_object(
            clause.category,
            is_atom,
            owner=f"{owner}: semantic clause",
        )
        variables = _pattern_variables(pattern)
        type_term = from_object(
            clause.type_expr,
            lambda name, bound=variables: name not in bound,
            owner=f"{owner}: semantic clause",
        )
        self.clauses.append((pattern, type_term, clause.category))

type_of

type_of(category: Term, line: int, col: int) -> Term

The semantic type of a ground category.

PARAMETER DESCRIPTION
category

The category.

TYPE: Term

line

Where it is used.

TYPE: int

col

Where it is used.

TYPE: int

RETURNS DESCRIPTION
Term

Its type, a ground term of the judgment's syntax.

RAISES DESCRIPTION
LexicalError

If no clause matches the category or one of its parts.

Source code in src/quivers/dsl/lexical/semantics.py
def type_of(self, category: Term, line: int, col: int) -> Term:
    """The semantic type of a ground category.

    Parameters
    ----------
    category : Term
        The category.
    line : int
        Where it is used.
    col : int
        Where it is used.

    Returns
    -------
    Term
        Its type, a ground term of the judgment's syntax.

    Raises
    ------
    LexicalError
        If no clause matches the category or one of its parts.
    """
    for pattern, type_term, _ in self.clauses:
        bindings = match(pattern, category)
        if bindings is None:
            continue
        types = {
            name: self.type_of(value, line, col) for name, value in bindings.items()
        }
        return substitute(type_term, types)
    raise LexicalError(
        f"{self.owner}: no semantics clause gives the type of category "
        f"{render(category)}",
        line,
        col,
    )

check

check(meaning: LetExprNode, category: Term, *, owner: str) -> None

Refuse a meaning without a typing at its category's type.

PARAMETER DESCRIPTION
meaning

The meaning.

TYPE: LetExprNode

category

Its category.

TYPE: Term

owner

The entry, for diagnostics.

TYPE: str

RAISES DESCRIPTION
LexicalError

If the meaning is not a term of the judgment's syntax, or has no derivation of the judgment at the category's type; the message names the type and the constraint that failed.

Source code in src/quivers/dsl/lexical/semantics.py
def check(
    self, meaning: surface.LetExprNode, category: Term, *, owner: str
) -> None:
    """Refuse a meaning without a typing at its category's type.

    Parameters
    ----------
    meaning : LetExprNode
        The meaning.
    category : Term
        Its category.
    owner : str
        The entry, for diagnostics.

    Raises
    ------
    LexicalError
        If the meaning is not a term of the judgment's syntax, or has no
        derivation of the judgment at the category's type; the message
        names the type and the constraint that failed.
    """
    line = getattr(meaning, "line", 0)
    col = getattr(meaning, "col", 0)
    expected = self.type_of(category, line, col)
    signature = self.system.signature
    judgment = self.declaration.judgment
    try:
        term = logical_form(meaning, signature)
        if not isinstance(term, SyntaxTerm):
            raise JudgmentFailure("a meaning is a closed term")
        goal = self.system.goal(
            judgment,
            ContextValue(entries=()),
            term,
            from_term(to_syntax(expected, signature)),
        )
        self.system.derivations(goal, limit=1)
    except JudgmentFailure as error:
        raise LexicalError(
            f"{owner}: its meaning has no derivation of {judgment} at "
            f"{render(expected)}, the type of {render(category)}: {error}",
            line,
            col,
        ) from error

SynthesisCall didactic-model

SynthesisCall(*, generator: str, argument: Term, owner: str, line: int = 0, col: int = 0)

Bases: Model

One meaning to synthesize.

PARAMETER DESCRIPTION
generator

The meta computation.

TYPE: str

argument

The semantic type it receives, a ground term.

TYPE: Term

owner

The entry the meaning is for, for diagnostics.

TYPE: str

line

The call's line.

TYPE: int DEFAULT: 0

col

The call's column.

TYPE: int DEFAULT: 0

Node didactic-model

Node(*, head: str, args: tuple[Term, ...] = (), form: Literal['atom', 'apply', 'slash', 'features', 'integer', 'string'] = 'atom', kind: Literal['node'] = 'node')

Bases: Term

An atom, an application, a slash, or an atom at feature values.

PARAMETER DESCRIPTION
head

The atom, the applied symbol, the slash (/ or \), or the featured atom.

TYPE: str

args

The arguments; empty for an atom.

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

form

How the source spells it: atom, apply, slash, features, integer, or string.

TYPE: Literal['atom', 'apply', 'slash', 'features', 'integer', 'string'] DEFAULT: 'atom'

Term didactic-model

Term()

Bases: TaggedUnion

A first-order term over a deduction's atoms.

Variable didactic-model

Variable(*, name: str, kind: Literal['variable'] = 'variable')

Bases: Term

A variable.

PARAMETER DESCRIPTION
name

The variable's name.

TYPE: str

CategoryRule didactic-model

CategoryRule(*, name: str, premises: tuple[Term, ...], conclusion: Term)

Bases: Model

A rule read on categories: premise categories to a conclusion category.

PARAMETER DESCRIPTION
name

The rule.

TYPE: str

premises

The category of each premise.

TYPE: tuple[Term, ...]

conclusion

The category of the conclusion.

TYPE: Term

binder_sets

binder_sets(binders: Mapping[str, str], sets: CategorySets, line: int, col: int) -> None

Refuse binders over undeclared sets.

PARAMETER DESCRIPTION
binders

Each category variable's set.

TYPE: Mapping[str, str]

sets

The deduction's sets.

TYPE: CategorySets

line

Where the binders are written.

TYPE: int

col

Where the binders are written.

TYPE: int

RAISES DESCRIPTION
LexicalError

If a set is undeclared.

Source code in src/quivers/dsl/lexical/categories.py
def binder_sets(
    binders: Mapping[str, str], sets: CategorySets, line: int, col: int
) -> None:
    """Refuse binders over undeclared sets.

    Parameters
    ----------
    binders : Mapping[str, str]
        Each category variable's set.
    sets : CategorySets
        The deduction's sets.
    line : int
        Where the binders are written.
    col : int
        Where the binders are written.

    Raises
    ------
    LexicalError
        If a set is undeclared.
    """
    for set_name in binders.values():
        sets.require(set_name, line, col)

empty_sets

empty_sets(owner: str) -> CategorySets

No category sets.

PARAMETER DESCRIPTION
owner

The deduction, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
CategorySets

The empty collection.

Source code in src/quivers/dsl/lexical/categories.py
def empty_sets(owner: str) -> CategorySets:
    """No category sets.

    Parameters
    ----------
    owner : str
        The deduction, for diagnostics.

    Returns
    -------
    CategorySets
        The empty collection.
    """
    return CategorySets((), lambda _: False, owner)

family_of_entry

family_of_entry(index: int) -> str

The weight family every instance of a written entry reads.

PARAMETER DESCRIPTION
index

The entry's position in the lexicon.

TYPE: int

RETURNS DESCRIPTION
str

__lexical_entry_<index>, a hidden name no written family uses.

Source code in src/quivers/dsl/lexical/entries.py
def family_of_entry(index: int) -> str:
    """The weight family every instance of a written entry reads.

    Parameters
    ----------
    index : int
        The entry's position in the lexicon.

    Returns
    -------
    str
        ``__lexical_entry_<index>``, a hidden name no written family uses.
    """
    return f"__lexical_entry_{index}"

family_of_instance

family_of_instance(index: int, assignment: Sequence[Term]) -> str

The weight family an instance of a per_instance entry reads.

The entry's family is indexed by the instantiation, as a rule schema's #[shared = F(n)] is by its parameters, so each assignment of categories to the entry's variables has a weight of its own, read by the instance however the entry is instantiated.

PARAMETER DESCRIPTION
index

The entry's position in the lexicon.

TYPE: int

assignment

The categories its variables take, in binder order.

TYPE: Sequence[Term]

RETURNS DESCRIPTION
str

__lexical_entry_<index>[c1,c2,...], the entry's hidden family at the rendered categories.

Source code in src/quivers/dsl/lexical/entries.py
def family_of_instance(index: int, assignment: Sequence[Term]) -> str:
    """The weight family an instance of a ``per_instance`` entry reads.

    The entry's family is indexed by the instantiation, as a rule schema's
    ``#[shared = F(n)]`` is by its parameters, so each assignment of
    categories to the entry's variables has a weight of its own, read by
    the instance however the entry is instantiated.

    Parameters
    ----------
    index : int
        The entry's position in the lexicon.
    assignment : Sequence[Term]
        The categories its variables take, in binder order.

    Returns
    -------
    str
        ``__lexical_entry_<index>[c1,c2,...]``, the entry's hidden family at
        the rendered categories.
    """
    return f"{family_of_entry(index)}[{','.join(render(c) for c in assignment)}]"

instances

instances(schema: Schema, sets: CategorySets, attested: Callable[[int], frozenset[Term]], synthesize: Callable[[str, Term, str, int, int], LetExprNode], *, depth_bound: int | None, owner: str) -> tuple[Instance, ...]

The instances of one schema.

PARAMETER DESCRIPTION
schema

The entry.

TYPE: Schema

sets

The deduction's category sets.

TYPE: CategorySets

attested

The categories the grammar attests up to a depth bound.

TYPE: Callable[[int], frozenset[Term]]

synthesize

Synthesizes a meaning: synthesize(generator, category, owner, line, col) runs the meta computation generator at the semantic type of category.

TYPE: Callable[[str, Term, str, int, int], LetExprNode]

depth_bound

The deduction's depth, if declared.

TYPE: int | None

owner

The deduction, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
tuple[Instance, ...]

One instance per word and assignment, in order.

RAISES DESCRIPTION
LexicalError

If a variable ranges over an undeclared set, over an infinite set with no bound, the category mentions a name that is neither an atom nor a variable, or the meaning uses a variable in a way no category spells.

Source code in src/quivers/dsl/lexical/entries.py
def instances(
    schema: Schema,
    sets: CategorySets,
    attested: Callable[[int], frozenset[Term]],
    synthesize: Callable[[str, Term, str, int, int], LetExprNode],
    *,
    depth_bound: int | None,
    owner: str,
) -> tuple[Instance, ...]:
    """The instances of one schema.

    Parameters
    ----------
    schema : Schema
        The entry.
    sets : CategorySets
        The deduction's category sets.
    attested : Callable[[int], frozenset[Term]]
        The categories the grammar attests up to a depth bound.
    synthesize : Callable[[str, Term, str, int, int], LetExprNode]
        Synthesizes a meaning: ``synthesize(generator, category, owner,
        line, col)`` runs the meta computation ``generator`` at the semantic
        type of ``category``.
    depth_bound : int | None
        The deduction's ``depth``, if declared.
    owner : str
        The deduction, for diagnostics.

    Returns
    -------
    tuple[Instance, ...]
        One instance per word and assignment, in order.

    Raises
    ------
    LexicalError
        If a variable ranges over an undeclared set, over an infinite set
        with no bound, the category mentions a name that is neither an atom
        nor a variable, or the meaning uses a variable in a way no category
        spells.
    """
    where = f"{owner}: lexicon entry {', '.join(repr(w) for w in schema.words)}"
    names = [b.name for b in schema.binders]
    if len(set(names)) != len(names):
        raise LexicalError(
            f"{where}: binds a category variable twice", schema.line, schema.col
        )
    free = [v for v in variables_of(schema.category) if v not in names]
    if free:
        raise LexicalError(
            f"{where}: its category names {free[0]!r}, which is neither an atom nor "
            "a variable its ∀ binds",
            schema.line,
            schema.col,
        )
    learnable = _flag(schema.options, "learnable")
    apart = _flag(schema.options, "per_instance")
    shared = _name(schema.options, "shared", where, schema.line, schema.col)
    if apart and shared:
        raise LexicalError(
            f"{where}: per_instance gives each instance a weight of its own, and "
            "shared one family for all; drop one of the two",
            schema.line,
            schema.col,
        )
    mode = _name(schema.options, "instantiate", where, schema.line, schema.col)
    if mode and mode not in INSTANTIATIONS:
        raise LexicalError(
            f"{where}: instantiate is {' or '.join(INSTANTIATIONS)}, not {mode!r}",
            schema.line,
            schema.col,
        )
    if mode and not schema.binders:
        raise LexicalError(
            f"{where}: instantiate applies to an entry with category variables",
            schema.line,
            schema.col,
        )
    bound = _number(schema.options, "bound", where, schema.line, schema.col)
    choices: list[tuple[Term, ...]] = []
    for binder in schema.binders:
        sets.require(binder.set_name, binder.line, binder.col)
        if binder.set_name in sets.finite:
            choices.append(sets.enumerate(binder.set_name))
            continue
        limit = bound if bound is not None else depth_bound
        if limit is None:
            raise LexicalError(
                f"{where}: {binder.name} ranges over {binder.set_name}, an infinite "
                "set, so its instances need a bound: give the entry #[bound=n] or "
                "the deduction a depth",
                binder.line,
                binder.col,
            )
        choices.append(
            tuple(
                sorted(
                    (
                        category
                        for category in attested(limit)
                        if depth(category) <= limit
                        and sets.contains(binder.set_name, category)
                    ),
                    key=render,
                )
            )
        )
    weights: tuple[str, ...] = ()
    own = learnable
    apart = apart and learnable
    if apart:
        own = False
    elif shared:
        weights = (shared,)
        own = False
    elif schema.binders and learnable:
        weights = (family_of_entry(schema.index),)
        own = False
    found: list[Instance] = []
    for assignment in product(*choices):
        mapping = dict(zip(names, assignment, strict=True))
        category = substitute(schema.category, mapping)
        meaning = _instantiate_meaning(schema.meaning, mapping, synthesize, where)
        for word in schema.words:
            found.append(
                Instance(
                    word=word,
                    category=category,
                    meaning=meaning,
                    learnable=own,
                    weights=(
                        (family_of_instance(schema.index, assignment),)
                        if apart
                        else weights
                    ),
                    apart=apart,
                    source=schema.index,
                    lazy=mode == "lazy",
                    line=schema.line,
                    col=schema.col,
                )
            )
    return tuple(found)

schemas

schemas(declaration: DeductionDecl, is_atom: Callable[[str], bool], templates: Mapping[str, LexicalTemplate], owner: str) -> tuple[Schema, ...]

Read each written entry as a schema, applying templates.

PARAMETER DESCRIPTION
declaration

The deduction.

TYPE: DeductionDecl

is_atom

Whether a name is one of its atoms.

TYPE: Callable[[str], bool]

templates

Its templates, by name.

TYPE: Mapping[str, LexicalTemplate]

owner

The deduction, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
tuple[Schema, ...]

One schema per written entry, in order.

RAISES DESCRIPTION
LexicalError

If an entry has an unknown option, or a latent (* or set of atoms) category with category variables or a template.

Source code in src/quivers/dsl/lexical/entries.py
def schemas(
    declaration: DeductionDecl,
    is_atom: Callable[[str], bool],
    templates: Mapping[str, LexicalTemplate],
    owner: str,
) -> tuple[Schema, ...]:
    """Read each written entry as a schema, applying templates.

    Parameters
    ----------
    declaration : DeductionDecl
        The deduction.
    is_atom : Callable[[str], bool]
        Whether a name is one of its atoms.
    templates : Mapping[str, LexicalTemplate]
        Its templates, by name.
    owner : str
        The deduction, for diagnostics.

    Returns
    -------
    tuple[Schema, ...]
        One schema per written entry, in order.

    Raises
    ------
    LexicalError
        If an entry has an unknown option, or a latent (``*`` or set of
        atoms) category with category variables or a template.
    """
    read: list[Schema] = []
    for index, entry in enumerate(declaration.lexicon):
        where = f"{owner}: lexicon entry {', '.join(repr(w) for w in entry.words)}"
        _check_options(entry.options, where, entry.line, entry.col)
        category = entry.category
        if isinstance(category, LexiconCategoryPolymorphic):
            binders = category.binders
            written = category.category
        elif isinstance(category, LexiconCategoryFixed):
            binders = ()
            written = category.category
        else:
            raise LexicalError(
                f"{where}: a latent category (`*` or a set of atoms) is not "
                "expanded with templates, category sets, or lexical rules; give "
                "the entry a category",
                entry.line,
                entry.col,
            )
        bound = frozenset(b.name for b in binders)
        template = _template_named(written, templates, is_atom)
        if template is not None:
            if binders:
                raise LexicalError(
                    f"{where}: names the template {template.name!r}, whose "
                    "category variables are its own",
                    entry.line,
                    entry.col,
                )
            _check_options(template.options, where, template.line, template.col)
            meaning = _apply_template(template, entry.lf)
            read.append(
                Schema(
                    words=entry.words,
                    binders=template.binders,
                    category=from_object(
                        template.category,
                        lambda name, b=frozenset(x.name for x in template.binders): (
                            name not in b and is_atom(name)
                        ),
                        owner=where,
                    ),
                    meaning=meaning,
                    options=(*template.options, *entry.options),
                    index=index,
                    line=entry.line,
                    col=entry.col,
                )
            )
            continue
        read.append(
            Schema(
                words=entry.words,
                binders=binders,
                category=from_object(
                    written,
                    lambda name, b=bound: name not in b and is_atom(name),
                    owner=where,
                ),
                meaning=entry.lf,
                options=entry.options,
                index=index,
                line=entry.line,
                col=entry.col,
            )
        )
    return tuple(read)

synthesis_calls

synthesis_calls(meaning: LetExprNode, variables: frozenset[str]) -> bool

Whether a meaning calls a meta computation on a category variable.

PARAMETER DESCRIPTION
meaning

The meaning.

TYPE: LetExprNode

variables

The category variables.

TYPE: frozenset[str]

RETURNS DESCRIPTION
bool

Whether some g[X] with X a variable occurs.

Source code in src/quivers/dsl/lexical/entries.py
def synthesis_calls(meaning: LetExprNode, variables: frozenset[str]) -> bool:
    """Whether a meaning calls a meta computation on a category variable.

    Parameters
    ----------
    meaning : LetExprNode
        The meaning.
    variables : frozenset[str]
        The category variables.

    Returns
    -------
    bool
        Whether some ``g[X]`` with ``X`` a variable occurs.
    """
    if isinstance(meaning, LetExprIndex):
        return _synthesis(meaning, variables) is not None or any(
            synthesis_calls(i, variables) for i in meaning.indices
        )
    if isinstance(meaning, LetExprCall):
        return any(synthesis_calls(a, variables) for a in meaning.args)
    return False

expand_lexical

expand_lexical(module: Module, *, module_name: str, file_path: str) -> LexicalExpansion

Expand every deduction of a module into a plain one.

PARAMETER DESCRIPTION
module

The module, its deductions composed.

TYPE: Module

module_name

The module's name, for the meta phase.

TYPE: str

file_path

The path recorded on diagnostics.

TYPE: str

RETURNS DESCRIPTION
LexicalExpansion

The module, each deduction that used lexical surface replaced by its expansion and followed by what its refinement generates, the refinements' forgetful maps, and the agenda plans.

RAISES DESCRIPTION
LexicalError

If any deduction's expansion is refused; the message names the deduction, the part refused, and the property it lacks.

Source code in src/quivers/dsl/lexical/expand.py
def expand_lexical(
    module: Module, *, module_name: str, file_path: str
) -> LexicalExpansion:
    """Expand every deduction of a module into a plain one.

    Parameters
    ----------
    module : Module
        The module, its deductions composed.
    module_name : str
        The module's name, for the meta phase.
    file_path : str
        The path recorded on diagnostics.

    Returns
    -------
    LexicalExpansion
        The module, each deduction that used lexical surface replaced by
        its expansion and followed by what its refinement generates, the
        refinements' forgetful maps, and the agenda plans.

    Raises
    ------
    LexicalError
        If any deduction's expansion is refused; the message names the
        deduction, the part refused, and the property it lacks.
    """
    deductions = {
        statement.name: statement
        for statement in module.statements
        if isinstance(statement, DeductionDecl)
    }
    if not any(uses_lexical_surface(d) for d in deductions.values()):
        return LexicalExpansion(module=module)
    expander = _Expander(module, deductions, module_name, file_path)
    statements: list[Statement] = []
    tests: list[TestDecl] = list(module.tests)
    # A refinement is placed after its base, whose generated computations
    # its inherited rules read.
    waiting: dict[str, list[DeductionDecl]] = {}
    placed: set[str] = set()

    def place(statement: Statement) -> None:
        if isinstance(statement, DeductionDecl) and uses_lexical_surface(statement):
            base = statement.refines
            if base and base in deductions and base not in placed:
                waiting.setdefault(base, []).append(statement)
                return
            expanded = expander.expanded(statement.name)
            statements.append(expanded.declaration)
            statements.extend(expanded.generated)
            tests.extend(expanded.tests)
        else:
            statements.append(statement)
        if isinstance(statement, DeductionDecl):
            placed.add(statement.name)
            for refinement in waiting.pop(statement.name, []):
                place(refinement)

    for statement in module.statements:
        place(statement)
    return LexicalExpansion(
        module=module.with_(statements=tuple(statements), tests=tuple(tests)),
        refinements=dict(expander.refinements),
        plans={
            name: done.plan
            for name, done in expander.done.items()
            if done.plan is not None
        },
    )

uses_lexical_surface

uses_lexical_surface(declaration: DeductionDecl) -> bool

Whether a deduction uses anything expansion rewrites.

PARAMETER DESCRIPTION
declaration

The deduction.

TYPE: DeductionDecl

RETURNS DESCRIPTION
bool

Whether it declares category sets, semantics, templates, lexical rules, featured atoms, or a base, or has a polymorphic entry or an entry naming a weight family.

Source code in src/quivers/dsl/lexical/expand.py
def uses_lexical_surface(declaration: DeductionDecl) -> bool:
    """Whether a deduction uses anything expansion rewrites.

    Parameters
    ----------
    declaration : DeductionDecl
        The deduction.

    Returns
    -------
    bool
        Whether it declares category sets, semantics, templates, lexical
        rules, featured atoms, or a base, or has a polymorphic entry or an
        entry naming a weight family.
    """
    return bool(
        declaration.category_sets
        or declaration.semantics is not None
        or declaration.templates
        or declaration.lexical_rules
        or declaration.features
        or declaration.refines
        or any(
            isinstance(entry.category, LexiconCategoryPolymorphic)
            or find_option(entry.options, "shared") is not None
            for entry in declaration.lexicon
        )
    )

featured_name

featured_name(atom: str, values: Sequence[str]) -> str

The atom a featured atom is at some feature values.

PARAMETER DESCRIPTION
atom

The featured atom.

TYPE: str

values

Its feature values, in order.

TYPE: Sequence[str]

RETURNS DESCRIPTION
str

atom__value1__value2..., a hidden name.

Source code in src/quivers/dsl/lexical/features.py
def featured_name(atom: str, values: Sequence[str]) -> str:
    """The atom a featured atom is at some feature values.

    Parameters
    ----------
    atom : str
        The featured atom.
    values : Sequence[str]
        Its feature values, in order.

    Returns
    -------
    str
        ``atom__value1__value2...``, a hidden name.
    """
    return "__".join((atom, *values))

instantiate_rules

instantiate_rules(rules: Sequence[SequentRule], features: Features, is_atom: Callable[[str], bool], owner: str) -> tuple[tuple[SequentRule, ...], dict[str, str]]

Each rule at every assignment of its feature variables.

PARAMETER DESCRIPTION
rules

The rules.

TYPE: Sequence[SequentRule]

features

The featured atoms.

TYPE: Features

is_atom

Whether a name is an atom.

TYPE: Callable[[str], bool]

owner

The deduction, for diagnostics.

TYPE: str

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

The rules over plain atoms, and each rule's source rule by name.

RAISES DESCRIPTION
LexicalError

If a featured atom is written bare or with values outside its sets, or a feature variable can take no value.

Source code in src/quivers/dsl/lexical/features.py
def instantiate_rules(
    rules: Sequence[SequentRule],
    features: Features,
    is_atom: Callable[[str], bool],
    owner: str,
) -> tuple[tuple[SequentRule, ...], dict[str, str]]:
    """Each rule at every assignment of its feature variables.

    Parameters
    ----------
    rules : Sequence[SequentRule]
        The rules.
    features : Features
        The featured atoms.
    is_atom : Callable[[str], bool]
        Whether a name is an atom.
    owner : str
        The deduction, for diagnostics.

    Returns
    -------
    tuple[tuple[SequentRule, ...], dict[str, str]]
        The rules over plain atoms, and each rule's source rule by name.

    Raises
    ------
    LexicalError
        If a featured atom is written bare or with values outside its
        sets, or a feature variable can take no value.
    """
    if not features.sets:
        return tuple(rules), {rule.name: rule.name for rule in rules}
    result: list[SequentRule] = []
    sources: dict[str, str] = {}
    for rule in rules:
        where = f"{owner}: rule {rule.name!r}"
        premises = [from_object(p, is_atom, owner=where) for p in rule.premises]
        conclusion = from_object(rule.conclusion, is_atom, owner=where)
        domains: dict[str, frozenset[str]] = {}
        for term in (*premises, conclusion):
            for name, allowed in features.variables(term).items():
                domains[name] = domains.get(name, allowed) & allowed
        empty = [name for name, allowed in domains.items() if not allowed]
        if empty:
            raise LexicalError(
                f"{where}: feature variable {empty[0]} fills features with no "
                "common value",
                rule.line,
                rule.col,
            )
        names = sorted(domains)
        for assignment in product(*(sorted(domains[n]) for n in names)):
            mapping: dict[str, Term] = {
                n: Node(head=v) for n, v in zip(names, assignment, strict=True)
            }
            name = "__".join((rule.name, *assignment)) if names else rule.name
            written = [
                features.ground(substitute(t, mapping), where, rule.line, rule.col)
                for t in premises
            ]
            concluded = features.ground(
                substitute(conclusion, mapping), where, rule.line, rule.col
            )
            result.append(
                rule.with_(
                    name=name,
                    premises=tuple(to_object(t, rule.line, rule.col) for t in written),
                    conclusion=to_object(concluded, rule.line, rule.col),
                )
            )
            sources[name] = rule.name
    return tuple(result), sources

read_features

read_features(declared: Sequence[AtomFeatures], sets: CategorySets, owner: str) -> Features

Read a deduction's featured atoms.

PARAMETER DESCRIPTION
declared

The featured atoms of its atoms lines.

TYPE: Sequence[AtomFeatures]

sets

Its category sets.

TYPE: CategorySets

owner

The deduction, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
Features

The featured atoms.

RAISES DESCRIPTION
LexicalError

If a feature's set is undeclared, infinite, or has a member that is not an atom, or an atom is declared with features twice.

Source code in src/quivers/dsl/lexical/features.py
def read_features(
    declared: Sequence[AtomFeatures], sets: CategorySets, owner: str
) -> Features:
    """Read a deduction's featured atoms.

    Parameters
    ----------
    declared : Sequence[AtomFeatures]
        The featured atoms of its atoms lines.
    sets : CategorySets
        Its category sets.
    owner : str
        The deduction, for diagnostics.

    Returns
    -------
    Features
        The featured atoms.

    Raises
    ------
    LexicalError
        If a feature's set is undeclared, infinite, or has a member that is
        not an atom, or an atom is declared with features twice.
    """
    feature_sets: dict[str, tuple[str, ...]] = {}
    values: dict[str, tuple[tuple[str, ...], ...]] = {}
    for item in declared:
        if item.atom in feature_sets:
            raise LexicalError(
                f"{owner}: {item.atom} is declared with features twice",
                item.line,
                item.col,
            )
        choices: list[tuple[str, ...]] = []
        for feature in item.features:
            sets.require(feature.set_name, feature.line, feature.col)
            if feature.set_name not in sets.finite:
                raise LexicalError(
                    f"{owner}: feature {feature.name or feature.set_name} of "
                    f"{item.atom} ranges over {feature.set_name}, an infinite set; "
                    "a feature's values are finitely many atoms",
                    feature.line,
                    feature.col,
                )
            members = sets.enumerate(feature.set_name)
            for member in members:
                if not isinstance(member, Node) or member.args:
                    raise LexicalError(
                        f"{owner}: {render(member)} in {feature.set_name} is not an "
                        "atom; a feature's values are atoms",
                        feature.line,
                        feature.col,
                    )
            choices.append(tuple(m.head for m in members if isinstance(m, Node)))
        feature_sets[item.atom] = tuple(f.set_name for f in item.features)
        values[item.atom] = tuple(choices)
    return Features(sets=feature_sets, values=values)

placeholder

placeholder(source: int, meaning_class: int) -> str

The atom standing for a lazily instantiated entry at one meaning.

PARAMETER DESCRIPTION
source

The entry's position in the lexicon.

TYPE: int

meaning_class

The position of the meaning (and the weights) among the entry's.

TYPE: int

RETURNS DESCRIPTION
str

__lazy_<source>_<meaning_class>, a hidden name.

Source code in src/quivers/dsl/lexical/lazy.py
def placeholder(source: int, meaning_class: int) -> str:
    """The atom standing for a lazily instantiated entry at one meaning.

    Parameters
    ----------
    source : int
        The entry's position in the lexicon.
    meaning_class : int
        The position of the meaning (and the weights) among the entry's.

    Returns
    -------
    str
        ``__lazy_<source>_<meaning_class>``, a hidden name.
    """
    return f"__lazy_{source}_{meaning_class}"

specialize

specialize(lazy: Sequence[Instance], rules: Sequence[SequentRule], is_atom: Callable[[str], bool], owner: str, *, wrap: Callable[[Term], Term] | None = None, suffix: str = 'lazy', per_word: bool = False) -> Specialization

The placeholder entries and specialized rules of lazy entries.

PARAMETER DESCRIPTION
lazy

The instances of every lazily instantiated entry.

TYPE: Sequence[Instance]

rules

The rules to specialize.

TYPE: Sequence[SequentRule]

is_atom

Whether a name is an atom.

TYPE: Callable[[str], bool]

owner

The deduction, for diagnostics.

TYPE: str

wrap

Wraps a lexical item's category when the rules take wrapped items (lexical rules in the chart), or None.

TYPE: Callable[[Term], Term] | None DEFAULT: None

suffix

What a specialized rule's name adds to its source's.

TYPE: str DEFAULT: 'lazy'

per_word

Whether each word of an entry has a placeholder of its own, so a rule that consumes one knows the word: a grammar normalized per left-hand side reads the consumed instance's production, which is the word's.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Specialization

The placeholders, the specialized rules, and their instances.

RAISES DESCRIPTION
LexicalError

If a premise that is a bare variable would be specialized while the variable also occurs inside a term of the rule.

Source code in src/quivers/dsl/lexical/lazy.py
def specialize(
    lazy: Sequence[Instance],
    rules: Sequence[SequentRule],
    is_atom: Callable[[str], bool],
    owner: str,
    *,
    wrap: Callable[[Term], Term] | None = None,
    suffix: str = "lazy",
    per_word: bool = False,
) -> Specialization:
    """The placeholder entries and specialized rules of lazy entries.

    Parameters
    ----------
    lazy : Sequence[Instance]
        The instances of every lazily instantiated entry.
    rules : Sequence[SequentRule]
        The rules to specialize.
    is_atom : Callable[[str], bool]
        Whether a name is an atom.
    owner : str
        The deduction, for diagnostics.
    wrap : Callable[[Term], Term] | None
        Wraps a lexical item's category when the rules take wrapped items
        (lexical rules in the chart), or ``None``.
    suffix : str
        What a specialized rule's name adds to its source's.
    per_word : bool
        Whether each word of an entry has a placeholder of its own, so a
        rule that consumes one knows the word: a grammar normalized per
        left-hand side reads the consumed instance's production, which is
        the word's.

    Returns
    -------
    Specialization
        The placeholders, the specialized rules, and their instances.

    Raises
    ------
    LexicalError
        If a premise that is a bare variable would be specialized while
        the variable also occurs inside a term of the rule.
    """
    if not lazy:
        return Specialization()
    read = [
        (
            rule,
            tuple(
                from_object(p, is_atom, owner=f"{owner}: rule {rule.name!r}")
                for p in rule.premises
            ),
            from_object(rule.conclusion, is_atom, owner=f"{owner}: rule {rule.name!r}"),
        )
        for rule in rules
    ]
    classes: dict[tuple[int, str, tuple[str, ...], bool, bool, str], int] = {}
    placeholders: dict[tuple[str, str], Instance] = {}
    names: dict[int, str] = {}
    for position, instance in enumerate(lazy):
        where = f"{owner}: lexicon entry {instance.word!r}"
        meaning = render(from_meaning(instance.meaning, owner=where))
        # An entry that weighs each instance apart has one placeholder for
        # all of them, which weighs nothing: the rules specialized to it
        # read the consumed instance's weight.
        key = (
            instance.source,
            meaning,
            () if instance.apart else instance.weights,
            instance.learnable,
            instance.apart,
            instance.word if per_word else "",
        )
        if key not in classes:
            classes[key] = sum(1 for k in classes if k[0] == instance.source)
        name = placeholder(instance.source, classes[key])
        names[position] = name
        placeholders.setdefault(
            (name, instance.word),
            instance.with_(
                category=Node(head=name),
                weights=() if instance.apart else instance.weights,
            ),
        )
    # One item per placeholder and category: the words a placeholder
    # covers share its item, so a rule takes it once.
    items: list[tuple[Instance, str]] = []
    seen: set[tuple[str, str]] = set()
    for position, instance in enumerate(lazy):
        mark = (names[position], render(instance.category))
        if mark not in seen:
            seen.add(mark)
            items.append((instance, names[position]))
    specialized: list[SequentRule] = []
    instances: dict[str, dict[int, Term]] = {}
    consumed: dict[str, tuple[tuple[str, str, Term], ...]] = {}
    arity = _span_arity(read)
    for rule, premises, conclusion in read:
        assignments = _assignments(premises, items, wrap, arity)
        if not assignments:
            continue
        _check_whole_items(rule, premises, conclusion, assignments, owner)
        for number, (chosen, unifier) in enumerate(assignments):
            made = _specialized_rule(
                rule,
                premises,
                conclusion,
                chosen,
                unifier,
                f"{rule.name}__{suffix}{number}",
                wrap,
            )
            specialized.append(made)
            instances[made.name] = {
                index: instance.category for index, (instance, _) in chosen.items()
            }
            consumed[made.name] = tuple(
                (name, instance.word, instance.category)
                for _, (instance, name) in sorted(chosen.items())
            )
    return Specialization(
        placeholders=tuple(placeholders.values()),
        rules=tuple(specialized),
        instances=instances,
        names=tuple(names[position] for position in range(len(lazy))),
        consumed=consumed,
    )

chart_atoms

chart_atoms(rules: Sequence[ReadRule]) -> tuple[str, ...]

The atoms the chart's lexical rules add to a deduction's plan.

PARAMETER DESCRIPTION
rules

The lexical rules in chart mode.

TYPE: Sequence[ReadRule]

RETURNS DESCRIPTION
tuple[str, ...]

The wrapper and one level atom per depth, or none without rules.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def chart_atoms(rules: Sequence[ReadRule]) -> tuple[str, ...]:
    """The atoms the chart's lexical rules add to a deduction's plan.

    Parameters
    ----------
    rules : Sequence[ReadRule]
        The lexical rules in ``chart`` mode.

    Returns
    -------
    tuple[str, ...]
        The wrapper and one level atom per depth, or none without rules.
    """
    if not rules:
        return ()
    return (WRAPPER, *(level(depth) for depth in range(chart_depth(rules) + 1)))

chart_depth

chart_depth(rules: Sequence[ReadRule]) -> int

The number of chart rule applications a lexical item may have behind it.

PARAMETER DESCRIPTION
rules

The lexical rules in chart mode.

TYPE: Sequence[ReadRule]

RETURNS DESCRIPTION
int

Their largest bound, or zero for none.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def chart_depth(rules: Sequence[ReadRule]) -> int:
    """The number of chart rule applications a lexical item may have behind it.

    Parameters
    ----------
    rules : Sequence[ReadRule]
        The lexical rules in ``chart`` mode.

    Returns
    -------
    int
        Their largest ``bound``, or zero for none.
    """
    return max((rule.bound for rule in rules), default=0)

chart_lexicon

chart_lexicon(found: Sequence[Instance], rules: Sequence[ReadRule]) -> tuple[tuple[Instance, str], ...]

The entries lexical rules in chart mode derive from a lexicon.

The chart rules close the lexicon as compiled rules do: each round applies every rule to the entries the previous round derived, up to the rules' largest bound.

PARAMETER DESCRIPTION
found

The lexicon's entries, their weights shared (share_weights).

TYPE: Sequence[Instance]

rules

The lexical rules in chart mode.

TYPE: Sequence[ReadRule]

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

Each derived entry, reading its source's weights and the rule's, and the rule deriving it, chain by chain.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def chart_lexicon(
    found: Sequence[Instance], rules: Sequence[ReadRule]
) -> tuple[tuple[Instance, str], ...]:
    """The entries lexical rules in chart mode derive from a lexicon.

    The chart rules close the lexicon as compiled rules do: each round
    applies every rule to the entries the previous round derived, up to the
    rules' largest ``bound``.

    Parameters
    ----------
    found : Sequence[Instance]
        The lexicon's entries, their weights shared (`share_weights`).
    rules : Sequence[ReadRule]
        The lexical rules in ``chart`` mode.

    Returns
    -------
    tuple[tuple[Instance, str], ...]
        Each derived entry, reading its source's weights and the rule's,
        and the rule deriving it, chain by chain.
    """
    derived: list[tuple[Instance, str]] = []
    frontier = list(found)
    for _ in range(chart_depth(rules)):
        step = [
            (result, rule.rule.name)
            for instance in frontier
            for rule in rules
            if (result := rule.apply(instance)) is not None
        ]
        derived.extend(step)
        frontier = [instance for instance, _ in step]
        if not frontier:
            break
    return tuple(derived)

chart_rules

chart_rules(rules: Sequence[ReadRule]) -> tuple[SequentRule, ...]

The chart rules lexical rules in chart mode become.

PARAMETER DESCRIPTION
rules

The lexical rules in chart mode.

TYPE: Sequence[ReadRule]

RETURNS DESCRIPTION
tuple[SequentRule, ...]

__lexical_lift, which unwraps a lexical item at any level, and one copy of each lexical rule per level below the largest bound, taking a wrapped item at its level to one at the next.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def chart_rules(rules: Sequence[ReadRule]) -> tuple[SequentRule, ...]:
    """The chart rules lexical rules in ``chart`` mode become.

    Parameters
    ----------
    rules : Sequence[ReadRule]
        The lexical rules in ``chart`` mode.

    Returns
    -------
    tuple[SequentRule, ...]
        ``__lexical_lift``, which unwraps a lexical item at any level, and
        one copy of each lexical rule per level below the largest bound,
        taking a wrapped item at its level to one at the next.
    """
    forms = any(rule.forms for rule in rules)
    variables: list[Term] = [
        Variable(name="I"),
        Variable(name="J"),
        Node(head=WRAPPER, args=(Variable(name="X"), Variable(name="L")), form="apply"),
    ]
    if forms:
        variables.append(Variable(name="F"))
    lift_conclusion: list[Term] = [
        Variable(name="I"),
        Variable(name="J"),
        Variable(name="X"),
    ]
    if forms:
        lift_conclusion.append(Variable(name="F"))
    generated = [
        SequentRule(
            name=LIFT,
            premises=(
                to_object(Node(head=SPAN_HEAD, args=tuple(variables), form="apply")),
            ),
            conclusion=to_object(
                Node(head=SPAN_HEAD, args=tuple(lift_conclusion), form="apply")
            ),
        )
    ]
    for depth in range(chart_depth(rules)):
        for rule in rules:
            premise, conclusion = rule.premise, rule.conclusion
            assert isinstance(premise, Node) and isinstance(conclusion, Node)
            generated.append(
                SequentRule(
                    name=level_rule(rule.rule.name, depth),
                    premises=(
                        to_object(
                            _at_level(premise, depth), rule.rule.line, rule.rule.col
                        ),
                    ),
                    conclusion=to_object(
                        _at_level(conclusion, depth + 1), rule.rule.line, rule.rule.col
                    ),
                    line=rule.rule.line,
                    col=rule.rule.col,
                    options=(
                        (
                            OptionEntry(
                                key="shared",
                                value=OptionName(value=family_of_rule(rule.rule.name)),
                            ),
                        )
                        if rule.learnable
                        else ()
                    ),
                )
            )
    return tuple(generated)

compile_lexical_rules

compile_lexical_rules(found: Sequence[Instance], rules: Sequence[ReadRule]) -> tuple[Instance, ...]

Close a lexicon under its compiled lexical rules.

Every entry first reads its own weight as the family of its written entry, so an entry a rule derives reads the same weight.

PARAMETER DESCRIPTION
found

The lexicon's entries.

TYPE: Sequence[Instance]

rules

The lexical rules in compile mode.

TYPE: Sequence[ReadRule]

RETURNS DESCRIPTION
tuple[Instance, ...]

The entries, then the derived ones, chain by chain up to the largest bound.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def compile_lexical_rules(
    found: Sequence[Instance], rules: Sequence[ReadRule]
) -> tuple[Instance, ...]:
    """Close a lexicon under its compiled lexical rules.

    Every entry first reads its own weight as the family of its written
    entry, so an entry a rule derives reads the same weight.

    Parameters
    ----------
    found : Sequence[Instance]
        The lexicon's entries.
    rules : Sequence[ReadRule]
        The lexical rules in ``compile`` mode.

    Returns
    -------
    tuple[Instance, ...]
        The entries, then the derived ones, chain by chain up to the
        largest ``bound``.
    """
    if not rules:
        return tuple(found)
    entries = list(share_weights(found))
    frontier = list(entries)
    for _ in range(max(rule.bound for rule in rules)):
        derived: list[Instance] = []
        for instance in frontier:
            for rule in rules:
                result = rule.apply(instance)
                if result is not None:
                    derived.append(result)
        entries.extend(derived)
        frontier = derived
        if not frontier:
            break
    return tuple(entries)

family_of_rule

family_of_rule(name: str) -> str

The weight family of a learnable lexical rule.

PARAMETER DESCRIPTION
name

The lexical rule.

TYPE: str

RETURNS DESCRIPTION
str

__lexical_rule_<name>, a hidden name no written family uses.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def family_of_rule(name: str) -> str:
    """The weight family of a learnable lexical rule.

    Parameters
    ----------
    name : str
        The lexical rule.

    Returns
    -------
    str
        ``__lexical_rule_<name>``, a hidden name no written family uses.
    """
    return f"__lexical_rule_{name}"

level

level(depth: int) -> str

The atom marking a lexical item a number of chart rule applications derived.

PARAMETER DESCRIPTION
depth

The number of applications.

TYPE: int

RETURNS DESCRIPTION
str

__lexical_level_<depth>, a hidden name.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def level(depth: int) -> str:
    """The atom marking a lexical item a number of chart rule applications derived.

    Parameters
    ----------
    depth : int
        The number of applications.

    Returns
    -------
    str
        ``__lexical_level_<depth>``, a hidden name.
    """
    return f"{LEVEL}_{depth}"

level_rule

level_rule(name: str, depth: int) -> str

The plan's copy of a chart lexical rule taking items at one level.

PARAMETER DESCRIPTION
name

The lexical rule.

TYPE: str

depth

The level of the items the copy takes.

TYPE: int

RETURNS DESCRIPTION
str

<name>__level<depth>.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def level_rule(name: str, depth: int) -> str:
    """The plan's copy of a chart lexical rule taking items at one level.

    Parameters
    ----------
    name : str
        The lexical rule.
    depth : int
        The level of the items the copy takes.

    Returns
    -------
    str
        ``<name>__level<depth>``.
    """
    return f"{name}__level{depth}"

share_weights

share_weights(found: Sequence[Instance]) -> tuple[Instance, ...]

Give every entry with a learned weight of its own its written entry's family.

An entry a lexical rule derives reads its source entry's weight, so the source's own weight becomes the family of its written entry, which both read.

PARAMETER DESCRIPTION
found

The lexicon's entries.

TYPE: Sequence[Instance]

RETURNS DESCRIPTION
tuple[Instance, ...]

The entries, each learnable one reading its written entry's family instead of a weight of its own.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def share_weights(found: Sequence[Instance]) -> tuple[Instance, ...]:
    """Give every entry with a learned weight of its own its written entry's family.

    An entry a lexical rule derives reads its source entry's weight, so the
    source's own weight becomes the family of its written entry, which both
    read.

    Parameters
    ----------
    found : Sequence[Instance]
        The lexicon's entries.

    Returns
    -------
    tuple[Instance, ...]
        The entries, each learnable one reading its written entry's family
        instead of a weight of its own.
    """
    return tuple(
        instance.with_(
            learnable=False,
            weights=(*instance.weights, family_of_entry(instance.source)),
        )
        if instance.learnable
        else instance
        for instance in found
    )

wrap

wrap(instance: Instance) -> Instance

A lexical entry whose item lexical rules in the chart apply to.

PARAMETER DESCRIPTION
instance

The entry.

TYPE: Instance

RETURNS DESCRIPTION
Instance

The entry with its category wrapped at level zero, __lexical_item(C, __lexical_level_0).

Source code in src/quivers/dsl/lexical/lexical_rules.py
def wrap(instance: Instance) -> Instance:
    """A lexical entry whose item lexical rules in the chart apply to.

    Parameters
    ----------
    instance : Instance
        The entry.

    Returns
    -------
    Instance
        The entry with its category wrapped at level zero,
        ``__lexical_item(C, __lexical_level_0)``.
    """
    return instance.with_(category=wrapped(instance.category, 0))

wrapped

wrapped(category: Term, depth: int) -> Term

A lexical item's category as the chart's lexical rules read it.

PARAMETER DESCRIPTION
category

The category.

TYPE: Term

depth

The number of chart rule applications that derived the item.

TYPE: int

RETURNS DESCRIPTION
Term

__lexical_item(category, __lexical_level_<depth>).

Source code in src/quivers/dsl/lexical/lexical_rules.py
def wrapped(category: Term, depth: int) -> Term:
    """A lexical item's category as the chart's lexical rules read it.

    Parameters
    ----------
    category : Term
        The category.
    depth : int
        The number of chart rule applications that derived the item.

    Returns
    -------
    Term
        ``__lexical_item(category, __lexical_level_<depth>)``.
    """
    return Node(head=WRAPPER, args=(category, Node(head=level(depth))), form="apply")

check_restriction

check_restriction(refinement: Refinement, rules: Sequence[SequentRule], entries: Sequence[LexiconEntry], base: DeductionDecl, is_atom: Callable[[str], bool], is_base_atom: Callable[[str], bool], sources: Mapping[str, str]) -> dict[str, str]

Check that a refinement only restricts its base; map its rules.

PARAMETER DESCRIPTION
refinement

The refinement's forgetful map on atoms.

TYPE: Refinement

rules

The refinement's expanded rules.

TYPE: Sequence[SequentRule]

entries

Its expanded lexicon.

TYPE: Sequence[LexiconEntry]

base

The expanded base.

TYPE: DeductionDecl

is_atom

Whether a name is an atom of the refinement.

TYPE: Callable[[str], bool]

is_base_atom

Whether a name is an atom of the base.

TYPE: Callable[[str], bool]

sources

Each expanded rule's written rule, for preferring a base rule of the same name.

TYPE: Mapping[str, str]

RETURNS DESCRIPTION
dict[str, str]

Each refined rule's base rule.

RAISES DESCRIPTION
LexicalError

If a rule's image is an instance of no base rule, naming the rule and its image, or an entry's image is no base entry.

Source code in src/quivers/dsl/lexical/refinement.py
def check_restriction(
    refinement: Refinement,
    rules: Sequence[SequentRule],
    entries: Sequence[LexiconEntry],
    base: DeductionDecl,
    is_atom: Callable[[str], bool],
    is_base_atom: Callable[[str], bool],
    sources: Mapping[str, str],
) -> dict[str, str]:
    """Check that a refinement only restricts its base; map its rules.

    Parameters
    ----------
    refinement : Refinement
        The refinement's forgetful map on atoms.
    rules : Sequence[SequentRule]
        The refinement's expanded rules.
    entries : Sequence[LexiconEntry]
        Its expanded lexicon.
    base : DeductionDecl
        The expanded base.
    is_atom : Callable[[str], bool]
        Whether a name is an atom of the refinement.
    is_base_atom : Callable[[str], bool]
        Whether a name is an atom of the base.
    sources : Mapping[str, str]
        Each expanded rule's written rule, for preferring a base rule of
        the same name.

    Returns
    -------
    dict[str, str]
        Each refined rule's base rule.

    Raises
    ------
    LexicalError
        If a rule's image is an instance of no base rule, naming the rule
        and its image, or an entry's image is no base entry.
    """
    owner = f"deduction {refinement.name!r}"
    base_rules = [
        (
            rule.name,
            tuple(from_object(p, is_base_atom, owner=owner) for p in rule.premises),
            from_object(rule.conclusion, is_base_atom, owner=owner),
        )
        for rule in base.rules
    ]
    images: dict[str, str] = {}
    for rule in rules:
        premises = tuple(
            refinement.forget(from_object(p, is_atom, owner=owner))
            for p in rule.premises
        )
        conclusion = refinement.forget(
            from_object(rule.conclusion, is_atom, owner=owner)
        )
        source = sources.get(rule.name, rule.name)
        candidates = sorted(base_rules, key=lambda item: item[0] != source)
        for name, base_premises, base_conclusion in candidates:
            if _instance_of((*premises, conclusion), (*base_premises, base_conclusion)):
                images[rule.name] = name
                break
        else:
            shown = ", ".join(render(p) for p in premises)
            raise LexicalError(
                f"{owner}: rule {rule.name!r} has no counterpart in {base.name!r}: "
                f"its image {shown} |- {render(conclusion)} is an instance of no "
                f"rule of {base.name!r}, so the refinement would not restrict it",
                rule.line,
                rule.col,
            )
    base_entries: set[tuple[str, Term, Term | None]] = set()
    for entry in base.lexicon:
        category = getattr(entry.category, "category", None)
        if category is None:
            continue
        for word in entry.words:
            base_entries.add(
                (
                    word,
                    from_object(category, is_base_atom, owner=owner),
                    None if entry.lf is None else from_meaning(entry.lf, owner=owner),
                )
            )
    for entry in entries:
        category = getattr(entry.category, "category", None)
        if category is None:
            raise LexicalError(
                f"{owner}: a latent category is not refined", entry.line, entry.col
            )
        image = refinement.forget(from_object(category, is_atom, owner=owner))
        meaning = None if entry.lf is None else from_meaning(entry.lf, owner=owner)
        for word in entry.words:
            if (word, image, meaning) not in base_entries:
                raise LexicalError(
                    f"{owner}: lexicon entry {word!r} : {render(image)} (forgotten) "
                    f"is no entry of {base.name!r}, so the refinement would add to "
                    "its lexicon",
                    entry.line,
                    entry.col,
                )
    return images

inherit

inherit(refined: DeductionDecl, base: DeductionDecl, featured: frozenset[str], is_base_atom: Callable[[str], bool]) -> DeductionDecl

A refinement with the parts of its base it does not restate.

PARAMETER DESCRIPTION
refined

The refinement as written.

TYPE: DeductionDecl

base

The base as written.

TYPE: DeductionDecl

featured

The atoms the refinement gives features.

TYPE: frozenset[str]

is_base_atom

Whether a name is an atom of the base.

TYPE: Callable[[str], bool]

RETURNS DESCRIPTION
DeductionDecl

The refinement with the base's atoms, binders, rules, entries, templates, lexical rules, category sets, and semantics it does not restate, keeping the refinement's own first. A base part that reads a featured atom bare is not inherited, since the refinement gives that atom no bare reading: a rule, lexical rule, or category set that names one, a template or entry whose category names one, and anything that ranges over or names a category set or template that is not inherited for that reason.

RAISES DESCRIPTION
LexicalError

If the base has a part the refinement cannot read: a lexicon file.

Source code in src/quivers/dsl/lexical/refinement.py
def inherit(
    refined: DeductionDecl,
    base: DeductionDecl,
    featured: frozenset[str],
    is_base_atom: Callable[[str], bool],
) -> DeductionDecl:
    """A refinement with the parts of its base it does not restate.

    Parameters
    ----------
    refined : DeductionDecl
        The refinement as written.
    base : DeductionDecl
        The base as written.
    featured : frozenset[str]
        The atoms the refinement gives features.
    is_base_atom : Callable[[str], bool]
        Whether a name is an atom of the base.

    Returns
    -------
    DeductionDecl
        The refinement with the base's atoms, binders, rules, entries,
        templates, lexical rules, category sets, and semantics it does not
        restate, keeping the refinement's own first. A base part that reads
        a featured atom bare is not inherited, since the refinement gives
        that atom no bare reading: a rule, lexical rule, or category set
        that names one, a template or entry whose category names one, and
        anything that ranges over or names a category set or template that
        is not inherited for that reason.

    Raises
    ------
    LexicalError
        If the base has a part the refinement cannot read: a lexicon file.
    """
    if base.lexicon_from_file is not None:
        raise LexicalError(
            f"deduction {refined.name!r} refines {base.name!r}, whose lexicon is "
            "read from a file; a refinement reads its base's entries",
            refined.line,
            refined.col,
        )
    restated_rules = {rule.name for rule in refined.rules}
    rules = [
        *refined.rules,
        *(
            rule
            for rule in base.rules
            if rule.name not in restated_rules
            and not _mentions(
                rule.premises + (rule.conclusion,), featured, is_base_atom
            )
        ),
    ]
    templates = {t.name for t in refined.templates}
    lexical_rules = {r.name for r in refined.lexical_rules}
    sets = {s.name for s in refined.category_sets}
    # The base's category sets and templates that read a featured atom
    # bare, directly or through another such set or template.
    unread: set[str] = set()
    pending = [
        *((s.name, s.members, ()) for s in base.category_sets if s.name not in sets),
        *(
            (x.name, (x.category,), x.binders)
            for x in base.templates
            if x.name not in templates
        ),
    ]
    changed = True
    while changed:
        changed = False
        for name, exprs, binders in pending:
            if name in unread:
                continue
            if _reads_bare(exprs, binders, featured, is_base_atom, unread):
                unread.add(name)
                changed = True
    entries = [*refined.lexicon]
    for entry in base.lexicon:
        category = getattr(entry.category, "category", None)
        binders = getattr(entry.category, "binders", ())
        if category is not None and _reads_bare(
            (category,), binders, featured, is_base_atom, unread
        ):
            continue
        entries.append(entry)
    atoms = [*refined.atoms]
    for atom in base.atoms:
        if atom not in atoms:
            atoms.append(atom)
    binders = [*refined.binders]
    for binder in base.binders:
        if binder not in binders:
            binders.append(binder)
    return refined.with_(
        atoms=tuple(atoms),
        binders=tuple(binders),
        rules=tuple(rules),
        lexicon=tuple(entries),
        templates=(
            *refined.templates,
            *(
                t
                for t in base.templates
                if t.name not in templates and t.name not in unread
            ),
        ),
        lexical_rules=(
            *refined.lexical_rules,
            *(
                r
                for r in base.lexical_rules
                if r.name not in lexical_rules
                and not _reads_bare(
                    (r.premise, r.conclusion), (), featured, is_base_atom, unread
                )
            ),
        ),
        category_sets=(
            *refined.category_sets,
            *(
                s
                for s in base.category_sets
                if s.name not in sets and s.name not in unread
            ),
        ),
        semantics=refined.semantics
        if refined.semantics is not None
        else base.semantics,
    )

transport_guard

transport_guard(declaration: QiecComputationDecl, name: str, base: str, refined: str, preimages: Mapping[str, tuple[str, ...]]) -> QiecComputationDecl

A guard over a base's items transported to a refinement's items.

A guard may not call another computation, so it cannot read its matched items through the forgetful map. It is transported the way Dagand and McBride transport a function defined by case analysis: each branch on a base constructor becomes a branch on every refined constructor that forgets to it, so the transported guard on a refined item decides what the base guard decides on its image.

PARAMETER DESCRIPTION
declaration

The base guard.

TYPE: QiecComputationDecl

name

The transported guard's name.

TYPE: str

base

The base deduction.

TYPE: str

refined

The refinement.

TYPE: str

preimages

Each base symbol with the refined symbols that forget to it.

TYPE: Mapping[str, tuple[str, ...]]

RETURNS DESCRIPTION
QiecComputationDecl

The transported guard.

RAISES DESCRIPTION
LexicalError

If the guard builds a base item, which has no single refinement.

Source code in src/quivers/dsl/lexical/refinement.py
def transport_guard(
    declaration: QiecComputationDecl,
    name: str,
    base: str,
    refined: str,
    preimages: Mapping[str, tuple[str, ...]],
) -> QiecComputationDecl:
    """A guard over a base's items transported to a refinement's items.

    A guard may not call another computation, so it cannot read its matched
    items through the forgetful map. It is transported the way Dagand and
    McBride transport a function defined by case analysis: each branch on a
    base constructor becomes a branch on every refined constructor that
    forgets to it, so the transported guard on a refined item decides what
    the base guard decides on its image.

    Parameters
    ----------
    declaration : QiecComputationDecl
        The base guard.
    name : str
        The transported guard's name.
    base : str
        The base deduction.
    refined : str
        The refinement.
    preimages : Mapping[str, tuple[str, ...]]
        Each base symbol with the refined symbols that forget to it.

    Returns
    -------
    QiecComputationDecl
        The transported guard.

    Raises
    ------
    LexicalError
        If the guard builds a base item, which has no single refinement.
    """
    base_item = member_name(base, "Item")
    refined_item = member_name(refined, "Item")

    def constructors(written: str) -> tuple[str, ...] | None:
        """The refined constructors a base constructor name stands for.

        Parameters
        ----------
        written : str
            A name.

        Returns
        -------
        tuple[str, ...] | None
            The refined constructors, or None for a name that is no base
            constructor.
        """
        prefix = f"{base}."
        if not written.startswith(prefix):
            return None
        symbol = written[len(prefix) :]
        if symbol not in preimages:
            return None
        return tuple(member_name(refined, s) for s in preimages[symbol])

    def visit(node: object) -> object:
        """Transport one node of the guard.

        Parameters
        ----------
        node : object
            A syntax node, a tuple of them, or a scalar.

        Returns
        -------
        object
            The transported node.
        """
        if isinstance(node, tuple):
            return tuple(visit(item) for item in node)
        if not isinstance(node, dx.Model):
            return node
        if isinstance(node, QiecTypeName) and node.name == base_item:
            return node.with_(name=refined_item)
        if isinstance(node, QiecConstructorPattern):
            images = constructors(node.constructor)
            moved = node.with_(arguments=tuple(visit(a) for a in node.arguments))
            if images is None:
                return moved
            return _alternatives(moved, images, "constructor")
        if isinstance(node, QiecNamePattern):
            images = constructors(node.name)
            if images is None:
                return node
            return _alternatives(node, images, "name")
        if isinstance(node, LetExprVar | LetExprCall):
            written = node.name if isinstance(node, LetExprVar) else node.func
            if constructors(written) is not None:
                raise LexicalError(
                    f"deduction {refined!r} inherits a rule guarded by "
                    f"{declaration.name!r}, which builds the {base_item} value "
                    f"{written}; a base item has no single refinement, so the "
                    "guard cannot be transported",
                    node.line,
                    node.col,
                )
        changed = {
            field: visit(getattr(node, field)) for field in type(node).__field_specs__
        }
        return node.with_(**changed)

    transported = visit(declaration)
    assert isinstance(transported, QiecComputationDecl)
    return transported.with_(name=name)

transport_weight

transport_weight(declaration: QiecComputationDecl, name: str, base: str, refined: str) -> str

A computed rule weight over a base's items, read on a refinement's.

The weight is a computation, which may call others, so it transports by precomposition: the transported weight forgets each item it is given and calls the base weight.

PARAMETER DESCRIPTION
declaration

The base weight.

TYPE: QiecComputationDecl

name

The transported weight's name.

TYPE: str

base

The base deduction.

TYPE: str

refined

The refinement.

TYPE: str

RETURNS DESCRIPTION
str

The transported weight's source.

RAISES DESCRIPTION
LexicalError

If the weight takes static parameters, which a rule weight does not.

Source code in src/quivers/dsl/lexical/refinement.py
def transport_weight(
    declaration: QiecComputationDecl, name: str, base: str, refined: str
) -> str:
    """A computed rule weight over a base's items, read on a refinement's.

    The weight is a computation, which may call others, so it transports
    by precomposition: the transported weight forgets each item it is
    given and calls the base weight.

    Parameters
    ----------
    declaration : QiecComputationDecl
        The base weight.
    name : str
        The transported weight's name.
    base : str
        The base deduction.
    refined : str
        The refinement.

    Returns
    -------
    str
        The transported weight's source.

    Raises
    ------
    LexicalError
        If the weight takes static parameters, which a rule weight does not.
    """
    if declaration.binders:
        raise LexicalError(
            f"rule weight {declaration.name!r} takes static parameters, which a "
            "rule weight does not",
            declaration.line,
            declaration.col,
        )
    base_item = member_name(base, "Item")
    refined_item = member_name(refined, "Item")
    forget = member_name(refined_item, "forget")
    parameters: list[str] = []
    lines: list[str] = []
    arguments: list[str] = []
    for parameter in declaration.parameters:
        written = static_argument_to_source(parameter.type_expr)
        if written == base_item:
            parameters.append(f"{parameter.name} : {refined_item}")
            local = f"{parameter.name}__base"
            lines.append(f"    let {local} <- {forget}({parameter.name})")
            arguments.append(local)
        else:
            parameters.append(f"{parameter.name} : {written}")
            arguments.append(parameter.name)
    result = static_argument_to_source(declaration.result_type)
    lines.append(f"    let weight <- {declaration.name}({', '.join(arguments)})")
    lines.append("    return weight")
    return (
        f"define {name}({', '.join(parameters)}) : {result} !{{}} =\n"
        + "\n".join(lines)
        + "\n"
    )

judgment_systems

judgment_systems(statements: Sequence[object]) -> dict[str, JudgmentSystem]

Build the judgment systems a module declares.

PARAMETER DESCRIPTION
statements

The module's statements.

TYPE: Sequence[object]

RETURNS DESCRIPTION
dict[str, JudgmentSystem]

Each judgment's system, by name.

RAISES DESCRIPTION
LexicalError

If a syntax or a judgment does not compile.

Source code in src/quivers/dsl/lexical/semantics.py
def judgment_systems(statements: Sequence[object]) -> dict[str, JudgmentSystem]:
    """Build the judgment systems a module declares.

    Parameters
    ----------
    statements : Sequence[object]
        The module's statements.

    Returns
    -------
    dict[str, JudgmentSystem]
        Each judgment's system, by name.

    Raises
    ------
    LexicalError
        If a syntax or a judgment does not compile.
    """
    signatures: dict[str, Signature] = {}
    judgments: list[surface.JudgmentDecl] = []
    for statement in statements:
        if isinstance(statement, surface.SyntaxDecl):
            try:
                signatures[statement.name] = _signature_from_declaration(statement)
            except CompileError as error:
                raise LexicalError(str(error), error.line, error.col) from error
        elif isinstance(statement, surface.JudgmentDecl):
            judgments.append(statement)
    try:
        return compile_judgments(judgments, signatures)
    except CompileError as error:
        raise LexicalError(str(error), error.line, error.col) from error

to_syntax

to_syntax(term: Term, signature: Signature) -> Term

A ground term as a term of a syntax.

PARAMETER DESCRIPTION
term

The term, over the syntax's constructors.

TYPE: Term

signature

The syntax.

TYPE: Signature

RETURNS DESCRIPTION
Term

The term.

RAISES DESCRIPTION
LexicalError

If the term has a variable or a head the syntax does not declare.

Source code in src/quivers/dsl/lexical/semantics.py
def to_syntax(term: Term, signature: Signature) -> SyntaxTerm:
    """A ground term as a term of a syntax.

    Parameters
    ----------
    term : Term
        The term, over the syntax's constructors.
    signature : Signature
        The syntax.

    Returns
    -------
    SyntaxTerm
        The term.

    Raises
    ------
    LexicalError
        If the term has a variable or a head the syntax does not declare.
    """
    if isinstance(term, Variable):
        raise LexicalError(f"semantic type {term.name!r} is not ground")
    assert isinstance(term, Node)
    if term.head not in signature.constructors:
        raise LexicalError(
            f"semantic type {render(term)} uses {term.head!r}, which is not a "
            f"constructor of syntax {signature.name!r}"
        )
    return SyntaxTerm(
        op=term.head, args=tuple(to_syntax(a, signature) for a in term.args)
    )

synthesize

synthesize(module: Module, calls: Sequence[SynthesisCall], *, module_name: str, file_path: str) -> tuple[LetExprNode, ...]

Run each synthesis call in the module's meta phase.

PARAMETER DESCRIPTION
module

The module, whose meta declarations the calls may use.

TYPE: Module

calls

The calls, in order.

TYPE: Sequence[SynthesisCall]

module_name

The module's name.

TYPE: str

file_path

The path recorded on diagnostics.

TYPE: str

RETURNS DESCRIPTION
tuple[LetExprNode, ...]

Each call's meaning, in order.

RAISES DESCRIPTION
LexicalError

If a generator is not a meta computation from one SynValue to a SynValue, refuses, fails, or returns syntax that is not a meaning.

Source code in src/quivers/dsl/lexical/synthesis.py
def synthesize(
    module: Module,
    calls: Sequence[SynthesisCall],
    *,
    module_name: str,
    file_path: str,
) -> tuple[LetExprNode, ...]:
    """Run each synthesis call in the module's meta phase.

    Parameters
    ----------
    module : Module
        The module, whose meta declarations the calls may use.
    calls : Sequence[SynthesisCall]
        The calls, in order.
    module_name : str
        The module's name.
    file_path : str
        The path recorded on diagnostics.

    Returns
    -------
    tuple[LetExprNode, ...]
        Each call's meaning, in order.

    Raises
    ------
    LexicalError
        If a generator is not a meta computation from one `SynValue` to a
        `SynValue`, refuses, fails, or returns syntax that is not a meaning.
    """
    if not calls:
        return ()
    phase = meta_phase._MetaPhase(module, module_name=module_name, file_path=file_path)
    wrappers: dict[str, QiecComputationDecl] = {}
    for call in calls:
        if call.generator in wrappers:
            continue
        try:
            generator = phase._generator(call.generator, call.line, call.col)
        except QiecDiagnosticError as error:
            raise LexicalError(
                f"{call.owner}: {error.message}", call.line, call.col
            ) from error
        if (
            len(generator.parameters) != 1
            or not _is_syntax_value(generator.parameters[0].type_expr)
            or not _is_syntax_value(generator.result_type)
            or generator.binders
        ):
            raise LexicalError(
                f"{call.owner}: {call.generator!r} synthesizes a meaning, so it "
                f"takes one {SYNTAX_VALUE} (the semantic type) and returns a "
                f"{SYNTAX_VALUE}",
                call.line,
                call.col,
            )
        wrappers[call.generator] = _wrapper(phase, call)
    module_part = (
        *phase._phase_one_data(),
        *phase.meta_declarations,
        *wrappers.values(),
    )
    meta_module = Module(statements=(*phase._library_part(module_part), *module_part))
    try:
        checked = meta_phase._check_meta_module(meta_module, file_path=file_path)
    except QiecDiagnosticError as error:
        raise LexicalError(error.message, error.line or 0, error.column or 0) from error
    universe = MetaUniverse(checked)
    meanings: list[LetExprNode] = []
    for call in calls:
        wrapper = wrappers[call.generator]
        try:
            argument = _quote(universe, call.argument)
            value = phase._evaluate(
                checked,
                wrapper.name,
                (argument,),
                code=LexicalError.code,
                line=call.line,
                col=call.col,
            )
            value = phase._outcome(
                universe,
                wrapper.name,
                value,
                code=LexicalError.code,
                line=call.line,
                col=call.col,
                subject=f"{call.generator}[{render(call.argument)}]",
            )
            meanings.append(_meaning(universe, value, call.line, call.col))
        except QiecDiagnosticError as error:
            raise LexicalError(
                f"{call.owner}: synthesizing its meaning by {call.generator!r} at "
                f"{render(call.argument)} failed: {error.message}",
                call.line,
                call.col,
            ) from error
        except MetaValueError as error:
            raise LexicalError(
                f"{call.owner}: {call.generator!r} returned {error}",
                call.line,
                call.col,
            ) from error
    return tuple(meanings)

apply

apply(head: str, *args: Term) -> Node

Apply a symbol.

PARAMETER DESCRIPTION
head

The symbol.

TYPE: str

*args

Its arguments.

TYPE: Term DEFAULT: ()

RETURNS DESCRIPTION
Node

The application.

Source code in src/quivers/dsl/lexical/terms.py
def apply(head: str, *args: Term) -> Node:
    """Apply a symbol.

    Parameters
    ----------
    head : str
        The symbol.
    *args : Term
        Its arguments.

    Returns
    -------
    Node
        The application.
    """
    return Node(head=head, args=args, form="apply")

atom

atom(name: str) -> Node

The atom of a name.

PARAMETER DESCRIPTION
name

The atom.

TYPE: str

RETURNS DESCRIPTION
Node

The atom as a term.

Source code in src/quivers/dsl/lexical/terms.py
def atom(name: str) -> Node:
    """The atom of a name.

    Parameters
    ----------
    name : str
        The atom.

    Returns
    -------
    Node
        The atom as a term.
    """
    return Node(head=name)

depth

depth(term: Term) -> int

The constructor depth of a term: an atom or a variable is 0.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
int

The depth.

Source code in src/quivers/dsl/lexical/terms.py
def depth(term: Term) -> int:
    """The constructor depth of a term: an atom or a variable is 0.

    Parameters
    ----------
    term : Term
        The term.

    Returns
    -------
    int
        The depth.
    """
    if isinstance(term, Variable):
        return 0
    assert isinstance(term, Node)
    if not term.args:
        return 0
    return 1 + max(depth(a) for a in term.args)

from_meaning

from_meaning(node: LetExprNode, *, owner: str, variables: frozenset[str] = frozenset()) -> Term

Read a lexical meaning as a term.

A name is a variable when it is one of variables (a template's parameter, a category variable); every other name is a constant: an atom, or a name a binder binds.

PARAMETER DESCRIPTION
node

The meaning.

TYPE: LetExprNode

owner

What the meaning belongs to, for diagnostics.

TYPE: str

variables

The names that are variables.

TYPE: frozenset[str] DEFAULT: frozenset()

RETURNS DESCRIPTION
Term

The term.

RAISES DESCRIPTION
LexicalError

If the meaning holds something other than constructor applications, names, integers, and strings.

Source code in src/quivers/dsl/lexical/terms.py
def from_meaning(
    node: LetExprNode,
    *,
    owner: str,
    variables: frozenset[str] = frozenset(),
) -> Term:
    """Read a lexical meaning as a term.

    A name is a variable when it is one of ``variables`` (a template's
    parameter, a category variable); every other name is a constant: an
    atom, or a name a binder binds.

    Parameters
    ----------
    node : LetExprNode
        The meaning.
    owner : str
        What the meaning belongs to, for diagnostics.
    variables : frozenset[str]
        The names that are variables.

    Returns
    -------
    Term
        The term.

    Raises
    ------
    LexicalError
        If the meaning holds something other than constructor
        applications, names, integers, and strings.
    """
    if isinstance(node, LetExprVar):
        if node.name in variables:
            return Variable(name=node.name)
        return atom(node.name)
    if isinstance(node, LetExprCall):
        if node.arg_names and any(node.arg_names):
            raise LexicalError(
                f"{owner}: a meaning applies {node.func!r} to positional arguments",
                node.line,
                node.col,
            )
        return Node(
            head=node.func,
            args=tuple(
                from_meaning(a, owner=owner, variables=variables) for a in node.args
            ),
            form="apply",
        )
    if isinstance(node, LetExprLiteral) and node.integral:
        return Node(head=str(int(node.value)), form="integer")
    if isinstance(node, LetExprString):
        return Node(head=node.value, form="string")
    raise LexicalError(
        f"{owner}: a meaning is a term of constructors, names, and integers, "
        f"not a {type(node).__name__}",
        _line(node),
        _col(node),
    )

from_object

from_object(expr: ObjectExpr, is_atom: Callable[[str], bool], *, owner: str) -> Term

Read an object expression as a term.

PARAMETER DESCRIPTION
expr

A category or an item.

TYPE: ObjectExpr

is_atom

Whether a bare name is an atom rather than a variable.

TYPE: Callable[[str], bool]

owner

What the expression belongs to, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
Term

The term.

RAISES DESCRIPTION
LexicalError

If the expression is not a category: a product, a coproduct, a space, or a schema spine.

Source code in src/quivers/dsl/lexical/terms.py
def from_object(
    expr: ObjectExpr, is_atom: Callable[[str], bool], *, owner: str
) -> Term:
    """Read an object expression as a term.

    Parameters
    ----------
    expr : ObjectExpr
        A category or an item.
    is_atom : Callable[[str], bool]
        Whether a bare name is an atom rather than a variable.
    owner : str
        What the expression belongs to, for diagnostics.

    Returns
    -------
    Term
        The term.

    Raises
    ------
    LexicalError
        If the expression is not a category: a product, a coproduct, a
        space, or a schema spine.
    """
    if isinstance(expr, TypeName):
        if expr.name.isdigit():
            return Node(head=expr.name, form="integer")
        if is_atom(expr.name):
            return atom(expr.name)
        return Variable(name=expr.name)
    if isinstance(expr, ObjectEffectApply):
        return Node(
            head=expr.effect,
            args=tuple(from_object(a, is_atom, owner=owner) for a in expr.args),
            form="apply",
        )
    if isinstance(expr, ObjectSlash):
        return Node(
            head=expr.direction,
            args=(
                from_object(expr.result, is_atom, owner=owner),
                from_object(expr.argument, is_atom, owner=owner),
            ),
            form="slash",
        )
    if isinstance(expr, ObjectFeatures):
        return Node(
            head=expr.atom,
            args=tuple(from_object(a, is_atom, owner=owner) for a in expr.features),
            form="features",
        )
    raise LexicalError(
        f"{owner}: a {type(expr).__name__} is not a category",
        _line(expr),
        _col(expr),
    )

match

match(pattern: Term, term: Term, bindings: Mapping[str, Term] | None = None) -> dict[str, Term] | None

Match a pattern against a term, binding the pattern's variables.

The term's own variables are constants to the match.

PARAMETER DESCRIPTION
pattern

The pattern.

TYPE: Term

term

The term.

TYPE: Term

bindings

Bindings that must hold.

TYPE: Mapping[str, Term] | None DEFAULT: None

RETURNS DESCRIPTION
dict[str, Term] | None

The bindings, or None when the term is no instance.

Source code in src/quivers/dsl/lexical/terms.py
def match(
    pattern: Term, term: Term, bindings: Mapping[str, Term] | None = None
) -> dict[str, Term] | None:
    """Match a pattern against a term, binding the pattern's variables.

    The term's own variables are constants to the match.

    Parameters
    ----------
    pattern : Term
        The pattern.
    term : Term
        The term.
    bindings : Mapping[str, Term] | None
        Bindings that must hold.

    Returns
    -------
    dict[str, Term] | None
        The bindings, or None when the term is no instance.
    """
    result = dict(bindings or {})

    def visit(p: Term, t: Term) -> bool:
        if isinstance(p, Variable):
            bound = result.get(p.name)
            if bound is None:
                result[p.name] = t
                return True
            return bound == t
        assert isinstance(p, Node)
        if not isinstance(t, Node):
            return False
        if p.head != t.head or p.form != t.form or len(p.args) != len(t.args):
            return False
        return all(visit(a, b) for a, b in zip(p.args, t.args, strict=True))

    return result if visit(pattern, term) else None

rename

rename(term: Term, suffix: str) -> Term

Rename every variable apart by a suffix.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

suffix

Appended to each variable's name.

TYPE: str

RETURNS DESCRIPTION
Term

The renamed term.

Source code in src/quivers/dsl/lexical/terms.py
def rename(term: Term, suffix: str) -> Term:
    """Rename every variable apart by a suffix.

    Parameters
    ----------
    term : Term
        The term.
    suffix : str
        Appended to each variable's name.

    Returns
    -------
    Term
        The renamed term.
    """
    return substitute(
        term, {name: Variable(name=name + suffix) for name in variables_of(term)}
    )

render

render(term: Term) -> str

Spell a term as source writes it.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
str

The spelling.

Source code in src/quivers/dsl/lexical/terms.py
def render(term: Term) -> str:
    """Spell a term as source writes it.

    Parameters
    ----------
    term : Term
        The term.

    Returns
    -------
    str
        The spelling.
    """
    if isinstance(term, Variable):
        return term.name
    assert isinstance(term, Node)
    if term.form == "string":
        return f'"{term.head}"'
    if not term.args:
        return term.head
    if term.form == "slash":
        left, right = term.args
        return f"({render(left)} {term.head} {render(right)})"
    if term.form == "features":
        return f"{term.head}[{', '.join(render(a) for a in term.args)}]"
    return f"{term.head}({', '.join(render(a) for a in term.args)})"

substitute

substitute(term: Term, mapping: Mapping[str, Term]) -> Term

Replace variables by terms.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

mapping

The replacement of each variable; others stay.

TYPE: Mapping[str, Term]

RETURNS DESCRIPTION
Term

The term after replacement.

Source code in src/quivers/dsl/lexical/terms.py
def substitute(term: Term, mapping: Mapping[str, Term]) -> Term:
    """Replace variables by terms.

    Parameters
    ----------
    term : Term
        The term.
    mapping : Mapping[str, Term]
        The replacement of each variable; others stay.

    Returns
    -------
    Term
        The term after replacement.
    """
    if isinstance(term, Variable):
        return mapping.get(term.name, term)
    assert isinstance(term, Node)
    if not term.args:
        return term
    return term.with_(args=tuple(substitute(a, mapping) for a in term.args))

to_meaning

to_meaning(term: Term, line: int = 0, col: int = 0) -> LetExprNode

Write a term as a lexical meaning.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

line

The line the expression carries.

TYPE: int DEFAULT: 0

col

The column the expression carries.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
LetExprNode

The meaning.

Source code in src/quivers/dsl/lexical/terms.py
def to_meaning(term: Term, line: int = 0, col: int = 0) -> LetExprNode:
    """Write a term as a lexical meaning.

    Parameters
    ----------
    term : Term
        The term.
    line : int
        The line the expression carries.
    col : int
        The column the expression carries.

    Returns
    -------
    LetExprNode
        The meaning.
    """
    if isinstance(term, Variable):
        return LetExprVar(name=term.name, line=line, col=col)
    assert isinstance(term, Node)
    if term.form == "integer":
        return LetExprLiteral(value=int(term.head), integral=True, line=line, col=col)
    if term.form == "string":
        return LetExprString(value=term.head, line=line, col=col)
    if not term.args and term.form != "apply":
        return LetExprVar(name=term.head, line=line, col=col)
    return LetExprCall(
        func=term.head,
        args=tuple(to_meaning(a, line, col) for a in term.args),
        line=line,
        col=col,
    )

to_object

to_object(term: Term, line: int = 0, col: int = 0) -> ObjectExpr

Write a term as an object expression.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

line

The line the expression carries.

TYPE: int DEFAULT: 0

col

The column the expression carries.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
ObjectExpr

The expression.

RAISES DESCRIPTION
LexicalError

If the term is a string, which no category spells.

Source code in src/quivers/dsl/lexical/terms.py
def to_object(term: Term, line: int = 0, col: int = 0) -> ObjectExpr:
    """Write a term as an object expression.

    Parameters
    ----------
    term : Term
        The term.
    line : int
        The line the expression carries.
    col : int
        The column the expression carries.

    Returns
    -------
    ObjectExpr
        The expression.

    Raises
    ------
    LexicalError
        If the term is a string, which no category spells.
    """
    if isinstance(term, Variable):
        return TypeName(name=term.name, line=line, col=col)
    assert isinstance(term, Node)
    if term.form in ("atom", "integer"):
        return TypeName(name=term.head, line=line, col=col)
    if term.form == "slash":
        result, argument = term.args
        assert term.head in ("/", "\\")
        return ObjectSlash(
            result=to_object(result, line, col),
            argument=to_object(argument, line, col),
            direction="/" if term.head == "/" else "\\",
            line=line,
            col=col,
        )
    if term.form == "features":
        return ObjectFeatures(
            atom=term.head,
            features=tuple(to_object(a, line, col) for a in term.args),
            line=line,
            col=col,
        )
    if term.form == "string":
        raise LexicalError(f"the string {term.head!r} is not a category", line, col)
    return ObjectEffectApply(
        effect=term.head,
        args=tuple(to_object(a, line, col) for a in term.args),
        line=line,
        col=col,
    )

unify

unify(left: Term, right: Term) -> dict[str, Term] | None

A most general unifier of two terms, with the occurs check.

PARAMETER DESCRIPTION
left

One term.

TYPE: Term

right

The other; its variables are distinct from the first's when the caller renamed them apart.

TYPE: Term

RETURNS DESCRIPTION
dict[str, Term] | None

The unifier, fully applied, or None when the terms do not unify.

Source code in src/quivers/dsl/lexical/terms.py
def unify(left: Term, right: Term) -> dict[str, Term] | None:
    """A most general unifier of two terms, with the occurs check.

    Parameters
    ----------
    left : Term
        One term.
    right : Term
        The other; its variables are distinct from the first's when the
        caller renamed them apart.

    Returns
    -------
    dict[str, Term] | None
        The unifier, fully applied, or None when the terms do not unify.
    """
    solution: dict[str, Term] = {}

    def walk(t: Term) -> Term:
        while isinstance(t, Variable) and t.name in solution:
            t = solution[t.name]
        return t

    def occurs(name: str, t: Term) -> bool:
        t = walk(t)
        if isinstance(t, Variable):
            return t.name == name
        assert isinstance(t, Node)
        return any(occurs(name, a) for a in t.args)

    def visit(a: Term, b: Term) -> bool:
        a, b = walk(a), walk(b)
        if isinstance(a, Variable) and isinstance(b, Variable) and a.name == b.name:
            return True
        if isinstance(a, Variable):
            if occurs(a.name, b):
                return False
            solution[a.name] = b
            return True
        if isinstance(b, Variable):
            return visit(b, a)
        assert isinstance(a, Node) and isinstance(b, Node)
        if a.head != b.head or a.form != b.form or len(a.args) != len(b.args):
            return False
        return all(visit(x, y) for x, y in zip(a.args, b.args, strict=True))

    if not visit(left, right):
        return None

    def resolve(t: Term) -> Term:
        t = walk(t)
        if isinstance(t, Variable):
            return t
        assert isinstance(t, Node)
        if not t.args:
            return t
        return t.with_(args=tuple(resolve(a) for a in t.args))

    return {name: resolve(value) for name, value in solution.items()}

variables_of

variables_of(term: Term) -> tuple[str, ...]

The variables of a term, in order of first occurrence.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
tuple[str, ...]

The variables.

Source code in src/quivers/dsl/lexical/terms.py
def variables_of(term: Term) -> tuple[str, ...]:
    """The variables of a term, in order of first occurrence.

    Parameters
    ----------
    term : Term
        The term.

    Returns
    -------
    tuple[str, ...]
        The variables.
    """
    found: dict[str, None] = {}

    def visit(t: Term) -> None:
        if isinstance(t, Variable):
            found.setdefault(t.name, None)
            return
        assert isinstance(t, Node)
        for a in t.args:
            visit(a)

    visit(term)
    return tuple(found)

attested_categories

attested_categories(seeds: Iterable[Term], rules: Sequence[CategoryRule], bound: int) -> frozenset[Term]

The categories a grammar attests up to a depth bound.

PARAMETER DESCRIPTION
seeds

The categories of the monomorphic lexical entries.

TYPE: Iterable[Term]

rules

The deduction's rules on categories.

TYPE: Sequence[CategoryRule]

bound

The largest constructor depth of a derived category.

TYPE: int

RETURNS DESCRIPTION
frozenset[Term]

Every derived category and every part of one.

Source code in src/quivers/dsl/lexical/universe.py
def attested_categories(
    seeds: Iterable[Term], rules: Sequence[CategoryRule], bound: int
) -> frozenset[Term]:
    """The categories a grammar attests up to a depth bound.

    Parameters
    ----------
    seeds : Iterable[Term]
        The categories of the monomorphic lexical entries.
    rules : Sequence[CategoryRule]
        The deduction's rules on categories.
    bound : int
        The largest constructor depth of a derived category.

    Returns
    -------
    frozenset[Term]
        Every derived category and every part of one.
    """
    derived: set[Term] = {s for s in seeds if not variables_of(s)}
    changed = True
    while changed:
        changed = False
        snapshot = tuple(derived)
        for rule in rules:
            for found in _conclusions(rule, snapshot):
                if depth(found) <= bound and found not in derived:
                    derived.add(found)
                    changed = True
    return frozenset(part for category in derived for part in subterms(category))

category_of

category_of(item: Term) -> Term | None

The category of a span item, or None for another item.

PARAMETER DESCRIPTION
item

An item pattern.

TYPE: Term

RETURNS DESCRIPTION
Term | None

Its category slot.

Source code in src/quivers/dsl/lexical/universe.py
def category_of(item: Term) -> Term | None:
    """The category of a span item, or None for another item.

    Parameters
    ----------
    item : Term
        An item pattern.

    Returns
    -------
    Term | None
        Its category slot.
    """
    if (
        isinstance(item, Node)
        and item.head == SPAN_HEAD
        and item.form == "apply"
        and len(item.args) in (3, 4)
    ):
        return item.args[2]
    return None

category_rule

category_rule(name: str, premises: Sequence[Term], conclusion: Term) -> CategoryRule | None

Read a rule on categories, when every item of it is a span.

PARAMETER DESCRIPTION
name

The rule.

TYPE: str

premises

Its premise items.

TYPE: Sequence[Term]

conclusion

Its conclusion item.

TYPE: Term

RETURNS DESCRIPTION
CategoryRule | None

The rule on categories, or None when an item is not a span.

Source code in src/quivers/dsl/lexical/universe.py
def category_rule(
    name: str, premises: Sequence[Term], conclusion: Term
) -> CategoryRule | None:
    """Read a rule on categories, when every item of it is a span.

    Parameters
    ----------
    name : str
        The rule.
    premises : Sequence[Term]
        Its premise items.
    conclusion : Term
        Its conclusion item.

    Returns
    -------
    CategoryRule | None
        The rule on categories, or None when an item is not a span.
    """
    categories = [category_of(p) for p in premises]
    result = category_of(conclusion)
    if result is None or any(c is None for c in categories):
        return None
    return CategoryRule(
        name=name,
        premises=tuple(c for c in categories if c is not None),
        conclusion=result,
    )

subterms

subterms(term: Term) -> Iterable[Term]

A ground term and every part of it.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

YIELDS DESCRIPTION
Term

Each subterm, the term first.

Source code in src/quivers/dsl/lexical/universe.py
def subterms(term: Term) -> Iterable[Term]:
    """A ground term and every part of it.

    Parameters
    ----------
    term : Term
        The term.

    Yields
    ------
    Term
        Each subterm, the term first.
    """
    yield term
    if isinstance(term, Node):
        for a in term.args:
            yield from subterms(a)

expand

Expand a module's deductions into plain ones.

expand_lexical runs before the structure layer, the meta phase, and the compiler, after deduction composition, so every engine and transpile target reads deductions with no category sets, semantics, templates, polymorphic entries, lexical rules, featured atoms, or refinements. A deduction that uses none of them is left exactly as written. For one that does, expansion:

  1. inherits, for a refinement, every part of its base it does not restate;
  2. reads its templates and entries as schemas, and instantiates each entry at every assignment of its category variables, synthesizing meanings by meta computations;
  3. checks every meaning against its category's semantic type, when the deduction declares semantics;
  4. closes the lexicon under its compiled lexical rules;
  5. instantiates its rules over feature variables, and writes every featured atom as the atom it stands for;
  6. adds the entries its lexical rules in chart mode derive, each naming its rule;
  7. for a refinement, checks that it only restricts its base and generates its forgetful map and the transport of the base's derived instances;
  8. for a deduction with a lazily instantiated entry or a lexical rule in chart mode, builds the agenda plan the agenda engine runs in its place (quivers.dsl.ast_nodes.plans): the placeholders and the rules specialized to them, and the wrapped lexical items with the lift and the chart rules. The plan's atoms and rules never leave the engine, so the deduction every other reader sees has every instance as an entry.

NORMALIZE_OPTION module-attribute

NORMALIZE_OPTION = 'normalize'

The option whose lhs reading groups productions by left-hand side.

LexicalExpansion didactic-model

LexicalExpansion(*, module: Module = field(opaque=True, extras=OPAQUE_BY_VALUE), refinements: Mapping[str, Refinement] = field(opaque=True, default_factory=dict, extras=OPAQUE_BY_VALUE), plans: Mapping[str, AgendaPlan] = field(opaque=True, default_factory=dict, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A module with plain deductions, the refinements it declares, and agenda plans.

PARAMETER DESCRIPTION
module

The module.

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

refinements

The forgetful map of each refined deduction, by name.

TYPE: Mapping[str, Refinement] DEFAULT: field(opaque=True, default_factory=dict, extras=OPAQUE_BY_VALUE)

plans

The deduction the agenda engine runs in place of each deduction with a lazily instantiated entry or a lexical rule in chart mode, by name.

TYPE: Mapping[str, AgendaPlan] DEFAULT: field(opaque=True, default_factory=dict, extras=OPAQUE_BY_VALUE)

uses_lexical_surface

uses_lexical_surface(declaration: DeductionDecl) -> bool

Whether a deduction uses anything expansion rewrites.

PARAMETER DESCRIPTION
declaration

The deduction.

TYPE: DeductionDecl

RETURNS DESCRIPTION
bool

Whether it declares category sets, semantics, templates, lexical rules, featured atoms, or a base, or has a polymorphic entry or an entry naming a weight family.

Source code in src/quivers/dsl/lexical/expand.py
def uses_lexical_surface(declaration: DeductionDecl) -> bool:
    """Whether a deduction uses anything expansion rewrites.

    Parameters
    ----------
    declaration : DeductionDecl
        The deduction.

    Returns
    -------
    bool
        Whether it declares category sets, semantics, templates, lexical
        rules, featured atoms, or a base, or has a polymorphic entry or an
        entry naming a weight family.
    """
    return bool(
        declaration.category_sets
        or declaration.semantics is not None
        or declaration.templates
        or declaration.lexical_rules
        or declaration.features
        or declaration.refines
        or any(
            isinstance(entry.category, LexiconCategoryPolymorphic)
            or find_option(entry.options, "shared") is not None
            for entry in declaration.lexicon
        )
    )

expand_lexical

expand_lexical(module: Module, *, module_name: str, file_path: str) -> LexicalExpansion

Expand every deduction of a module into a plain one.

PARAMETER DESCRIPTION
module

The module, its deductions composed.

TYPE: Module

module_name

The module's name, for the meta phase.

TYPE: str

file_path

The path recorded on diagnostics.

TYPE: str

RETURNS DESCRIPTION
LexicalExpansion

The module, each deduction that used lexical surface replaced by its expansion and followed by what its refinement generates, the refinements' forgetful maps, and the agenda plans.

RAISES DESCRIPTION
LexicalError

If any deduction's expansion is refused; the message names the deduction, the part refused, and the property it lacks.

Source code in src/quivers/dsl/lexical/expand.py
def expand_lexical(
    module: Module, *, module_name: str, file_path: str
) -> LexicalExpansion:
    """Expand every deduction of a module into a plain one.

    Parameters
    ----------
    module : Module
        The module, its deductions composed.
    module_name : str
        The module's name, for the meta phase.
    file_path : str
        The path recorded on diagnostics.

    Returns
    -------
    LexicalExpansion
        The module, each deduction that used lexical surface replaced by
        its expansion and followed by what its refinement generates, the
        refinements' forgetful maps, and the agenda plans.

    Raises
    ------
    LexicalError
        If any deduction's expansion is refused; the message names the
        deduction, the part refused, and the property it lacks.
    """
    deductions = {
        statement.name: statement
        for statement in module.statements
        if isinstance(statement, DeductionDecl)
    }
    if not any(uses_lexical_surface(d) for d in deductions.values()):
        return LexicalExpansion(module=module)
    expander = _Expander(module, deductions, module_name, file_path)
    statements: list[Statement] = []
    tests: list[TestDecl] = list(module.tests)
    # A refinement is placed after its base, whose generated computations
    # its inherited rules read.
    waiting: dict[str, list[DeductionDecl]] = {}
    placed: set[str] = set()

    def place(statement: Statement) -> None:
        if isinstance(statement, DeductionDecl) and uses_lexical_surface(statement):
            base = statement.refines
            if base and base in deductions and base not in placed:
                waiting.setdefault(base, []).append(statement)
                return
            expanded = expander.expanded(statement.name)
            statements.append(expanded.declaration)
            statements.extend(expanded.generated)
            tests.extend(expanded.tests)
        else:
            statements.append(statement)
        if isinstance(statement, DeductionDecl):
            placed.add(statement.name)
            for refinement in waiting.pop(statement.name, []):
                place(refinement)

    for statement in module.statements:
        place(statement)
    return LexicalExpansion(
        module=module.with_(statements=tuple(statements), tests=tuple(tests)),
        refinements=dict(expander.refinements),
        plans={
            name: done.plan
            for name, done in expander.done.items()
            if done.plan is not None
        },
    )

refinement

Refinements: deductions that add features to the atoms of a base.

refines Base makes a deduction an ornament of Base's item family [@dagand2014transporting]: it declares features on some of the base's atoms (atoms NP[num : Num]), so each refined category is a base category with feature values, and the refined deduction's rules and lexicon are those of the base written over refined categories. The erasure of the ornament, the forgetful map, sends NP__sg (NP[sg]) to NP and every other symbol to itself.

A refinement inherits every part of the base it does not restate: rules, entries, templates, lexical rules, category sets, and semantics. A base rule or entry that mentions an atom the refinement gives features is inherited only when restated, since its features are not determined; a rule is restated by declaring one of the same name. The compiler checks the restriction: the forgetful image of every rule of the refined deduction is an instance of a rule of the base, and the image of every lexical entry is an entry of the base, so the image of every refined derivation is a base derivation and the refined grammar's language is a subset of the base's.

The forgetful map is generated on items, as the derived instance R.Item.forget (class Forget of the meta library), and on host derivations, as Refinement.forget_derivation. Functions over the base's items transport along it: every class the base derives for its item family is derived for the refinement's, a signature morphism (Quote, Include) by Dagand and McBride's transport, which keeps the base's algebra and recurs over the refined family, and a module test states that the transported reification agrees with the base's after forgetting.

Derivation didactic-model

Derivation(*, item: Hashable = field(opaque=True, extras=OPAQUE_BY_IDENTITY), rule: str = '', premises: tuple[Derivation, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A derivation read off a chart: an item, its rule, its premises.

PARAMETER DESCRIPTION
item

The item derived, in the chart's representation. It may be any hashable host value and is compared by identity.

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

rule

The rule applied, or empty for a lexical axiom.

TYPE: str DEFAULT: ''

premises

The derivations of its premises, in order.

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

Refinement didactic-model

Refinement(*, name: str, base: str, atom_images: Mapping[str, str] = field(opaque=True, extras=OPAQUE_BY_VALUE), rule_images: Mapping[str, str] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The forgetful map of one refinement.

PARAMETER DESCRIPTION
name

The refined deduction.

TYPE: str

base

The deduction it refines.

TYPE: str

atom_images

Each atom of the refinement that is not one of the base's, with the base atom it forgets to.

TYPE: Mapping[str, str] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

rule_images

Each rule of the refinement with the base rule it maps to.

TYPE: Mapping[str, str] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

forget

forget(term: Term) -> Term

The forgetful image of a category, item, or rule pattern.

PARAMETER DESCRIPTION
term

A term of the refinement.

TYPE: Term

RETURNS DESCRIPTION
Term

The base term.

Source code in src/quivers/dsl/lexical/refinement.py
def forget(self, term: Term) -> Term:
    """The forgetful image of a category, item, or rule pattern.

    Parameters
    ----------
    term : Term
        A term of the refinement.

    Returns
    -------
    Term
        The base term.
    """
    if isinstance(term, Variable):
        return term
    assert isinstance(term, Node)
    head = self.atom_images.get(term.head, term.head)
    if not term.args:
        return term if head == term.head else Node(head=head)
    return term.with_(head=head, args=tuple(self.forget(a) for a in term.args))

forget_item

forget_item(item: Hashable) -> Hashable

The forgetful image of a chart item, as the agenda engine holds it.

PARAMETER DESCRIPTION
item

A refined item: a tuple whose atoms are ("atom", name).

TYPE: Hashable

RETURNS DESCRIPTION
Hashable

The base item.

Source code in src/quivers/dsl/lexical/refinement.py
def forget_item(self, item: Hashable) -> Hashable:
    """The forgetful image of a chart item, as the agenda engine holds it.

    Parameters
    ----------
    item : Hashable
        A refined item: a tuple whose atoms are ``("atom", name)``.

    Returns
    -------
    Hashable
        The base item.
    """
    if not isinstance(item, tuple) or not item:
        return item
    if len(item) == 2 and item[0] == "atom" and isinstance(item[1], str):
        return ("atom", self.atom_images.get(item[1], item[1]))
    head = item[0]
    if isinstance(head, str):
        head = self.atom_images.get(head, head)
    return (head, *(self.forget_item(part) for part in item[1:]))

forget_derivation

forget_derivation(derivation: Derivation) -> Derivation

The forgetful image of a derivation.

PARAMETER DESCRIPTION
derivation

A derivation in the refined deduction's chart.

TYPE: Derivation

RETURNS DESCRIPTION
Derivation

Its image: every item forgotten, every rule its base rule.

RAISES DESCRIPTION
LexicalError

If the derivation applies a rule the refinement does not have.

Source code in src/quivers/dsl/lexical/refinement.py
def forget_derivation(self, derivation: Derivation) -> Derivation:
    """The forgetful image of a derivation.

    Parameters
    ----------
    derivation : Derivation
        A derivation in the refined deduction's chart.

    Returns
    -------
    Derivation
        Its image: every item forgotten, every rule its base rule.

    Raises
    ------
    LexicalError
        If the derivation applies a rule the refinement does not have.
    """
    rule = derivation.rule
    if rule:
        if rule not in self.rule_images:
            raise LexicalError(
                f"deduction {self.name!r} has no rule {rule!r} to forget"
            )
        rule = self.rule_images[rule]
    return Derivation(
        item=self.forget_item(derivation.item),
        rule=rule,
        premises=tuple(self.forget_derivation(p) for p in derivation.premises),
    )

inherit

inherit(refined: DeductionDecl, base: DeductionDecl, featured: frozenset[str], is_base_atom: Callable[[str], bool]) -> DeductionDecl

A refinement with the parts of its base it does not restate.

PARAMETER DESCRIPTION
refined

The refinement as written.

TYPE: DeductionDecl

base

The base as written.

TYPE: DeductionDecl

featured

The atoms the refinement gives features.

TYPE: frozenset[str]

is_base_atom

Whether a name is an atom of the base.

TYPE: Callable[[str], bool]

RETURNS DESCRIPTION
DeductionDecl

The refinement with the base's atoms, binders, rules, entries, templates, lexical rules, category sets, and semantics it does not restate, keeping the refinement's own first. A base part that reads a featured atom bare is not inherited, since the refinement gives that atom no bare reading: a rule, lexical rule, or category set that names one, a template or entry whose category names one, and anything that ranges over or names a category set or template that is not inherited for that reason.

RAISES DESCRIPTION
LexicalError

If the base has a part the refinement cannot read: a lexicon file.

Source code in src/quivers/dsl/lexical/refinement.py
def inherit(
    refined: DeductionDecl,
    base: DeductionDecl,
    featured: frozenset[str],
    is_base_atom: Callable[[str], bool],
) -> DeductionDecl:
    """A refinement with the parts of its base it does not restate.

    Parameters
    ----------
    refined : DeductionDecl
        The refinement as written.
    base : DeductionDecl
        The base as written.
    featured : frozenset[str]
        The atoms the refinement gives features.
    is_base_atom : Callable[[str], bool]
        Whether a name is an atom of the base.

    Returns
    -------
    DeductionDecl
        The refinement with the base's atoms, binders, rules, entries,
        templates, lexical rules, category sets, and semantics it does not
        restate, keeping the refinement's own first. A base part that reads
        a featured atom bare is not inherited, since the refinement gives
        that atom no bare reading: a rule, lexical rule, or category set
        that names one, a template or entry whose category names one, and
        anything that ranges over or names a category set or template that
        is not inherited for that reason.

    Raises
    ------
    LexicalError
        If the base has a part the refinement cannot read: a lexicon file.
    """
    if base.lexicon_from_file is not None:
        raise LexicalError(
            f"deduction {refined.name!r} refines {base.name!r}, whose lexicon is "
            "read from a file; a refinement reads its base's entries",
            refined.line,
            refined.col,
        )
    restated_rules = {rule.name for rule in refined.rules}
    rules = [
        *refined.rules,
        *(
            rule
            for rule in base.rules
            if rule.name not in restated_rules
            and not _mentions(
                rule.premises + (rule.conclusion,), featured, is_base_atom
            )
        ),
    ]
    templates = {t.name for t in refined.templates}
    lexical_rules = {r.name for r in refined.lexical_rules}
    sets = {s.name for s in refined.category_sets}
    # The base's category sets and templates that read a featured atom
    # bare, directly or through another such set or template.
    unread: set[str] = set()
    pending = [
        *((s.name, s.members, ()) for s in base.category_sets if s.name not in sets),
        *(
            (x.name, (x.category,), x.binders)
            for x in base.templates
            if x.name not in templates
        ),
    ]
    changed = True
    while changed:
        changed = False
        for name, exprs, binders in pending:
            if name in unread:
                continue
            if _reads_bare(exprs, binders, featured, is_base_atom, unread):
                unread.add(name)
                changed = True
    entries = [*refined.lexicon]
    for entry in base.lexicon:
        category = getattr(entry.category, "category", None)
        binders = getattr(entry.category, "binders", ())
        if category is not None and _reads_bare(
            (category,), binders, featured, is_base_atom, unread
        ):
            continue
        entries.append(entry)
    atoms = [*refined.atoms]
    for atom in base.atoms:
        if atom not in atoms:
            atoms.append(atom)
    binders = [*refined.binders]
    for binder in base.binders:
        if binder not in binders:
            binders.append(binder)
    return refined.with_(
        atoms=tuple(atoms),
        binders=tuple(binders),
        rules=tuple(rules),
        lexicon=tuple(entries),
        templates=(
            *refined.templates,
            *(
                t
                for t in base.templates
                if t.name not in templates and t.name not in unread
            ),
        ),
        lexical_rules=(
            *refined.lexical_rules,
            *(
                r
                for r in base.lexical_rules
                if r.name not in lexical_rules
                and not _reads_bare(
                    (r.premise, r.conclusion), (), featured, is_base_atom, unread
                )
            ),
        ),
        category_sets=(
            *refined.category_sets,
            *(
                s
                for s in base.category_sets
                if s.name not in sets and s.name not in unread
            ),
        ),
        semantics=refined.semantics
        if refined.semantics is not None
        else base.semantics,
    )

check_restriction

check_restriction(refinement: Refinement, rules: Sequence[SequentRule], entries: Sequence[LexiconEntry], base: DeductionDecl, is_atom: Callable[[str], bool], is_base_atom: Callable[[str], bool], sources: Mapping[str, str]) -> dict[str, str]

Check that a refinement only restricts its base; map its rules.

PARAMETER DESCRIPTION
refinement

The refinement's forgetful map on atoms.

TYPE: Refinement

rules

The refinement's expanded rules.

TYPE: Sequence[SequentRule]

entries

Its expanded lexicon.

TYPE: Sequence[LexiconEntry]

base

The expanded base.

TYPE: DeductionDecl

is_atom

Whether a name is an atom of the refinement.

TYPE: Callable[[str], bool]

is_base_atom

Whether a name is an atom of the base.

TYPE: Callable[[str], bool]

sources

Each expanded rule's written rule, for preferring a base rule of the same name.

TYPE: Mapping[str, str]

RETURNS DESCRIPTION
dict[str, str]

Each refined rule's base rule.

RAISES DESCRIPTION
LexicalError

If a rule's image is an instance of no base rule, naming the rule and its image, or an entry's image is no base entry.

Source code in src/quivers/dsl/lexical/refinement.py
def check_restriction(
    refinement: Refinement,
    rules: Sequence[SequentRule],
    entries: Sequence[LexiconEntry],
    base: DeductionDecl,
    is_atom: Callable[[str], bool],
    is_base_atom: Callable[[str], bool],
    sources: Mapping[str, str],
) -> dict[str, str]:
    """Check that a refinement only restricts its base; map its rules.

    Parameters
    ----------
    refinement : Refinement
        The refinement's forgetful map on atoms.
    rules : Sequence[SequentRule]
        The refinement's expanded rules.
    entries : Sequence[LexiconEntry]
        Its expanded lexicon.
    base : DeductionDecl
        The expanded base.
    is_atom : Callable[[str], bool]
        Whether a name is an atom of the refinement.
    is_base_atom : Callable[[str], bool]
        Whether a name is an atom of the base.
    sources : Mapping[str, str]
        Each expanded rule's written rule, for preferring a base rule of
        the same name.

    Returns
    -------
    dict[str, str]
        Each refined rule's base rule.

    Raises
    ------
    LexicalError
        If a rule's image is an instance of no base rule, naming the rule
        and its image, or an entry's image is no base entry.
    """
    owner = f"deduction {refinement.name!r}"
    base_rules = [
        (
            rule.name,
            tuple(from_object(p, is_base_atom, owner=owner) for p in rule.premises),
            from_object(rule.conclusion, is_base_atom, owner=owner),
        )
        for rule in base.rules
    ]
    images: dict[str, str] = {}
    for rule in rules:
        premises = tuple(
            refinement.forget(from_object(p, is_atom, owner=owner))
            for p in rule.premises
        )
        conclusion = refinement.forget(
            from_object(rule.conclusion, is_atom, owner=owner)
        )
        source = sources.get(rule.name, rule.name)
        candidates = sorted(base_rules, key=lambda item: item[0] != source)
        for name, base_premises, base_conclusion in candidates:
            if _instance_of((*premises, conclusion), (*base_premises, base_conclusion)):
                images[rule.name] = name
                break
        else:
            shown = ", ".join(render(p) for p in premises)
            raise LexicalError(
                f"{owner}: rule {rule.name!r} has no counterpart in {base.name!r}: "
                f"its image {shown} |- {render(conclusion)} is an instance of no "
                f"rule of {base.name!r}, so the refinement would not restrict it",
                rule.line,
                rule.col,
            )
    base_entries: set[tuple[str, Term, Term | None]] = set()
    for entry in base.lexicon:
        category = getattr(entry.category, "category", None)
        if category is None:
            continue
        for word in entry.words:
            base_entries.add(
                (
                    word,
                    from_object(category, is_base_atom, owner=owner),
                    None if entry.lf is None else from_meaning(entry.lf, owner=owner),
                )
            )
    for entry in entries:
        category = getattr(entry.category, "category", None)
        if category is None:
            raise LexicalError(
                f"{owner}: a latent category is not refined", entry.line, entry.col
            )
        image = refinement.forget(from_object(category, is_atom, owner=owner))
        meaning = None if entry.lf is None else from_meaning(entry.lf, owner=owner)
        for word in entry.words:
            if (word, image, meaning) not in base_entries:
                raise LexicalError(
                    f"{owner}: lexicon entry {word!r} : {render(image)} (forgotten) "
                    f"is no entry of {base.name!r}, so the refinement would add to "
                    "its lexicon",
                    entry.line,
                    entry.col,
                )
    return images

transport_guard

transport_guard(declaration: QiecComputationDecl, name: str, base: str, refined: str, preimages: Mapping[str, tuple[str, ...]]) -> QiecComputationDecl

A guard over a base's items transported to a refinement's items.

A guard may not call another computation, so it cannot read its matched items through the forgetful map. It is transported the way Dagand and McBride transport a function defined by case analysis: each branch on a base constructor becomes a branch on every refined constructor that forgets to it, so the transported guard on a refined item decides what the base guard decides on its image.

PARAMETER DESCRIPTION
declaration

The base guard.

TYPE: QiecComputationDecl

name

The transported guard's name.

TYPE: str

base

The base deduction.

TYPE: str

refined

The refinement.

TYPE: str

preimages

Each base symbol with the refined symbols that forget to it.

TYPE: Mapping[str, tuple[str, ...]]

RETURNS DESCRIPTION
QiecComputationDecl

The transported guard.

RAISES DESCRIPTION
LexicalError

If the guard builds a base item, which has no single refinement.

Source code in src/quivers/dsl/lexical/refinement.py
def transport_guard(
    declaration: QiecComputationDecl,
    name: str,
    base: str,
    refined: str,
    preimages: Mapping[str, tuple[str, ...]],
) -> QiecComputationDecl:
    """A guard over a base's items transported to a refinement's items.

    A guard may not call another computation, so it cannot read its matched
    items through the forgetful map. It is transported the way Dagand and
    McBride transport a function defined by case analysis: each branch on a
    base constructor becomes a branch on every refined constructor that
    forgets to it, so the transported guard on a refined item decides what
    the base guard decides on its image.

    Parameters
    ----------
    declaration : QiecComputationDecl
        The base guard.
    name : str
        The transported guard's name.
    base : str
        The base deduction.
    refined : str
        The refinement.
    preimages : Mapping[str, tuple[str, ...]]
        Each base symbol with the refined symbols that forget to it.

    Returns
    -------
    QiecComputationDecl
        The transported guard.

    Raises
    ------
    LexicalError
        If the guard builds a base item, which has no single refinement.
    """
    base_item = member_name(base, "Item")
    refined_item = member_name(refined, "Item")

    def constructors(written: str) -> tuple[str, ...] | None:
        """The refined constructors a base constructor name stands for.

        Parameters
        ----------
        written : str
            A name.

        Returns
        -------
        tuple[str, ...] | None
            The refined constructors, or None for a name that is no base
            constructor.
        """
        prefix = f"{base}."
        if not written.startswith(prefix):
            return None
        symbol = written[len(prefix) :]
        if symbol not in preimages:
            return None
        return tuple(member_name(refined, s) for s in preimages[symbol])

    def visit(node: object) -> object:
        """Transport one node of the guard.

        Parameters
        ----------
        node : object
            A syntax node, a tuple of them, or a scalar.

        Returns
        -------
        object
            The transported node.
        """
        if isinstance(node, tuple):
            return tuple(visit(item) for item in node)
        if not isinstance(node, dx.Model):
            return node
        if isinstance(node, QiecTypeName) and node.name == base_item:
            return node.with_(name=refined_item)
        if isinstance(node, QiecConstructorPattern):
            images = constructors(node.constructor)
            moved = node.with_(arguments=tuple(visit(a) for a in node.arguments))
            if images is None:
                return moved
            return _alternatives(moved, images, "constructor")
        if isinstance(node, QiecNamePattern):
            images = constructors(node.name)
            if images is None:
                return node
            return _alternatives(node, images, "name")
        if isinstance(node, LetExprVar | LetExprCall):
            written = node.name if isinstance(node, LetExprVar) else node.func
            if constructors(written) is not None:
                raise LexicalError(
                    f"deduction {refined!r} inherits a rule guarded by "
                    f"{declaration.name!r}, which builds the {base_item} value "
                    f"{written}; a base item has no single refinement, so the "
                    "guard cannot be transported",
                    node.line,
                    node.col,
                )
        changed = {
            field: visit(getattr(node, field)) for field in type(node).__field_specs__
        }
        return node.with_(**changed)

    transported = visit(declaration)
    assert isinstance(transported, QiecComputationDecl)
    return transported.with_(name=name)

transport_weight

transport_weight(declaration: QiecComputationDecl, name: str, base: str, refined: str) -> str

A computed rule weight over a base's items, read on a refinement's.

The weight is a computation, which may call others, so it transports by precomposition: the transported weight forgets each item it is given and calls the base weight.

PARAMETER DESCRIPTION
declaration

The base weight.

TYPE: QiecComputationDecl

name

The transported weight's name.

TYPE: str

base

The base deduction.

TYPE: str

refined

The refinement.

TYPE: str

RETURNS DESCRIPTION
str

The transported weight's source.

RAISES DESCRIPTION
LexicalError

If the weight takes static parameters, which a rule weight does not.

Source code in src/quivers/dsl/lexical/refinement.py
def transport_weight(
    declaration: QiecComputationDecl, name: str, base: str, refined: str
) -> str:
    """A computed rule weight over a base's items, read on a refinement's.

    The weight is a computation, which may call others, so it transports
    by precomposition: the transported weight forgets each item it is
    given and calls the base weight.

    Parameters
    ----------
    declaration : QiecComputationDecl
        The base weight.
    name : str
        The transported weight's name.
    base : str
        The base deduction.
    refined : str
        The refinement.

    Returns
    -------
    str
        The transported weight's source.

    Raises
    ------
    LexicalError
        If the weight takes static parameters, which a rule weight does not.
    """
    if declaration.binders:
        raise LexicalError(
            f"rule weight {declaration.name!r} takes static parameters, which a "
            "rule weight does not",
            declaration.line,
            declaration.col,
        )
    base_item = member_name(base, "Item")
    refined_item = member_name(refined, "Item")
    forget = member_name(refined_item, "forget")
    parameters: list[str] = []
    lines: list[str] = []
    arguments: list[str] = []
    for parameter in declaration.parameters:
        written = static_argument_to_source(parameter.type_expr)
        if written == base_item:
            parameters.append(f"{parameter.name} : {refined_item}")
            local = f"{parameter.name}__base"
            lines.append(f"    let {local} <- {forget}({parameter.name})")
            arguments.append(local)
        else:
            parameters.append(f"{parameter.name} : {written}")
            arguments.append(parameter.name)
    result = static_argument_to_source(declaration.result_type)
    lines.append(f"    let weight <- {declaration.name}({', '.join(arguments)})")
    lines.append("    return weight")
    return (
        f"define {name}({', '.join(parameters)}) : {result} !{{}} =\n"
        + "\n".join(lines)
        + "\n"
    )

categories

Declared category sets: regular sets of terms over a deduction's atoms.

categories Conj = S, N, Bwd(Conj, Arg) declares the least set of terms holding S, N, and every Bwd(c, a) with c in Conj and a in Arg. A member names a set (itself or another) wherever it takes any element of that set, so a declaration is a regular tree grammar whose nonterminals are the sets. Membership of a term is decided by recursion on the term; a set is finite when no set reaches itself through a member, and a finite set is enumerated.

CategorySets

CategorySets(declarations: Iterable[CategorySetDecl], is_atom: Callable[[str], bool], owner: str)

The category sets of one deduction.

PARAMETER DESCRIPTION
declarations

The categories lines.

TYPE: Iterable[CategorySetDecl]

is_atom

Whether a name is one of the deduction's atoms.

TYPE: Callable[[str], bool]

owner

The deduction, for diagnostics.

TYPE: str

RAISES DESCRIPTION
LexicalError

If two sets share a name, a set is named like an atom, a member names something that is neither an atom nor a set, or a set is a member of itself without a constructor in between (so membership would not be decided by recursion on terms).

Source code in src/quivers/dsl/lexical/categories.py
def __init__(
    self,
    declarations: Iterable[CategorySetDecl],
    is_atom: Callable[[str], bool],
    owner: str,
) -> None:
    self.owner = owner
    decls = tuple(declarations)
    self.declarations: dict[str, CategorySetDecl] = {}
    for decl in decls:
        if decl.name in self.declarations:
            raise LexicalError(
                f"{owner}: category set {decl.name!r} is declared twice",
                decl.line,
                decl.col,
            )
        if is_atom(decl.name):
            raise LexicalError(
                f"{owner}: category set {decl.name!r} is named like an atom",
                decl.line,
                decl.col,
            )
        self.declarations[decl.name] = decl
    names = frozenset(self.declarations)
    self.members: dict[str, tuple[Term, ...]] = {}
    for decl in decls:
        members: list[Term] = []
        for expr in decl.members:
            term = from_object(
                expr,
                lambda name: is_atom(name) or name in names,
                owner=f"{owner}: category set {decl.name!r}",
            )
            stray = [
                variable
                for variable in _variables(term)
                if variable not in names and not is_atom(variable)
            ]
            if stray:
                raise LexicalError(
                    f"{owner}: category set {decl.name!r} names "
                    f"{stray[0]!r}, which is neither an atom nor a category set",
                    decl.line,
                    decl.col,
                )
            members.append(term)
        self.members[decl.name] = tuple(members)
    self._check_productive()
    self._memo: dict[tuple[str, Term], bool] = {}

finite cached property

finite: frozenset[str]

The sets no set reaches itself from: the finite ones.

RETURNS DESCRIPTION
frozenset[str]

Their names.

__contains__

__contains__(name: str) -> bool

Whether a set of that name is declared.

PARAMETER DESCRIPTION
name

The name.

TYPE: str

RETURNS DESCRIPTION
bool

Whether it names a set.

Source code in src/quivers/dsl/lexical/categories.py
def __contains__(self, name: str) -> bool:
    """Whether a set of that name is declared.

    Parameters
    ----------
    name : str
        The name.

    Returns
    -------
    bool
        Whether it names a set.
    """
    return name in self.declarations

require

require(name: str, line: int, col: int) -> None

Refuse a name that is no declared set.

PARAMETER DESCRIPTION
name

The name.

TYPE: str

line

Where it is used.

TYPE: int

col

Where it is used.

TYPE: int

RAISES DESCRIPTION
LexicalError

If no category set has that name.

Source code in src/quivers/dsl/lexical/categories.py
def require(self, name: str, line: int, col: int) -> None:
    """Refuse a name that is no declared set.

    Parameters
    ----------
    name : str
        The name.
    line : int
        Where it is used.
    col : int
        Where it is used.

    Raises
    ------
    LexicalError
        If no category set has that name.
    """
    if name not in self.members:
        declared = ", ".join(sorted(self.members)) or "none"
        raise LexicalError(
            f"{self.owner}: {name!r} is not a declared category set "
            f"(declared: {declared})",
            line,
            col,
        )

contains

contains(name: str, term: Term) -> bool

Whether a ground term belongs to a set.

PARAMETER DESCRIPTION
name

The set.

TYPE: str

term

The term.

TYPE: Term

RETURNS DESCRIPTION
bool

Membership.

Source code in src/quivers/dsl/lexical/categories.py
def contains(self, name: str, term: Term) -> bool:
    """Whether a ground term belongs to a set.

    Parameters
    ----------
    name : str
        The set.
    term : Term
        The term.

    Returns
    -------
    bool
        Membership.
    """
    key = (name, term)
    cached = self._memo.get(key)
    if cached is not None:
        return cached
    result = any(self._matches(member, term) for member in self.members[name])
    self._memo[key] = result
    return result

enumerate

enumerate(name: str) -> tuple[Term, ...]

Every member of a finite set, in declaration order.

PARAMETER DESCRIPTION
name

The set.

TYPE: str

RETURNS DESCRIPTION
tuple[Term, ...]

Its members, each once.

RAISES DESCRIPTION
LexicalError

If the set is infinite.

Source code in src/quivers/dsl/lexical/categories.py
def enumerate(self, name: str) -> tuple[Term, ...]:
    """Every member of a finite set, in declaration order.

    Parameters
    ----------
    name : str
        The set.

    Returns
    -------
    tuple[Term, ...]
        Its members, each once.

    Raises
    ------
    LexicalError
        If the set is infinite.
    """
    if name not in self.finite:
        decl = self.declarations[name]
        raise LexicalError(
            f"{self.owner}: category set {name!r} contains itself under a "
            "constructor, so it is infinite and has no list of members",
            decl.line,
            decl.col,
        )
    found: dict[Term, None] = {}
    for member in self.members[name]:
        for term in self._expand(member):
            found.setdefault(term, None)
    return tuple(found)

describe

describe(name: str) -> str

Spell a set's declaration.

PARAMETER DESCRIPTION
name

The set.

TYPE: str

RETURNS DESCRIPTION
str

Name = m1, m2, ....

Source code in src/quivers/dsl/lexical/categories.py
def describe(self, name: str) -> str:
    """Spell a set's declaration.

    Parameters
    ----------
    name : str
        The set.

    Returns
    -------
    str
        ``Name = m1, m2, ...``.
    """
    return f"{name} = " + ", ".join(render(m) for m in self.members[name])

empty_sets

empty_sets(owner: str) -> CategorySets

No category sets.

PARAMETER DESCRIPTION
owner

The deduction, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
CategorySets

The empty collection.

Source code in src/quivers/dsl/lexical/categories.py
def empty_sets(owner: str) -> CategorySets:
    """No category sets.

    Parameters
    ----------
    owner : str
        The deduction, for diagnostics.

    Returns
    -------
    CategorySets
        The empty collection.
    """
    return CategorySets((), lambda _: False, owner)

binder_sets

binder_sets(binders: Mapping[str, str], sets: CategorySets, line: int, col: int) -> None

Refuse binders over undeclared sets.

PARAMETER DESCRIPTION
binders

Each category variable's set.

TYPE: Mapping[str, str]

sets

The deduction's sets.

TYPE: CategorySets

line

Where the binders are written.

TYPE: int

col

Where the binders are written.

TYPE: int

RAISES DESCRIPTION
LexicalError

If a set is undeclared.

Source code in src/quivers/dsl/lexical/categories.py
def binder_sets(
    binders: Mapping[str, str], sets: CategorySets, line: int, col: int
) -> None:
    """Refuse binders over undeclared sets.

    Parameters
    ----------
    binders : Mapping[str, str]
        Each category variable's set.
    sets : CategorySets
        The deduction's sets.
    line : int
        Where the binders are written.
    col : int
        Where the binders are written.

    Raises
    ------
    LexicalError
        If a set is undeclared.
    """
    for set_name in binders.values():
        sets.require(set_name, line, col)

universe

The categories a deduction attests: the range of an infinite category set.

A category variable over a finite set takes each member of the set. Over an infinite set it takes the members the grammar attests: the categories the deduction's rules derive from the categories of its monomorphic lexical entries, together with every part of one, up to a constructor depth bound. The derivation is read on categories alone, with positions and meanings ignored, so the attested categories include every category a chart over any sentence can hold within the bound.

SPAN_HEAD module-attribute

SPAN_HEAD = 'span'

The head of the items a lexicon yields: span(i, j, category[, meaning]).

CategoryRule didactic-model

CategoryRule(*, name: str, premises: tuple[Term, ...], conclusion: Term)

Bases: Model

A rule read on categories: premise categories to a conclusion category.

PARAMETER DESCRIPTION
name

The rule.

TYPE: str

premises

The category of each premise.

TYPE: tuple[Term, ...]

conclusion

The category of the conclusion.

TYPE: Term

category_of

category_of(item: Term) -> Term | None

The category of a span item, or None for another item.

PARAMETER DESCRIPTION
item

An item pattern.

TYPE: Term

RETURNS DESCRIPTION
Term | None

Its category slot.

Source code in src/quivers/dsl/lexical/universe.py
def category_of(item: Term) -> Term | None:
    """The category of a span item, or None for another item.

    Parameters
    ----------
    item : Term
        An item pattern.

    Returns
    -------
    Term | None
        Its category slot.
    """
    if (
        isinstance(item, Node)
        and item.head == SPAN_HEAD
        and item.form == "apply"
        and len(item.args) in (3, 4)
    ):
        return item.args[2]
    return None

category_rule

category_rule(name: str, premises: Sequence[Term], conclusion: Term) -> CategoryRule | None

Read a rule on categories, when every item of it is a span.

PARAMETER DESCRIPTION
name

The rule.

TYPE: str

premises

Its premise items.

TYPE: Sequence[Term]

conclusion

Its conclusion item.

TYPE: Term

RETURNS DESCRIPTION
CategoryRule | None

The rule on categories, or None when an item is not a span.

Source code in src/quivers/dsl/lexical/universe.py
def category_rule(
    name: str, premises: Sequence[Term], conclusion: Term
) -> CategoryRule | None:
    """Read a rule on categories, when every item of it is a span.

    Parameters
    ----------
    name : str
        The rule.
    premises : Sequence[Term]
        Its premise items.
    conclusion : Term
        Its conclusion item.

    Returns
    -------
    CategoryRule | None
        The rule on categories, or None when an item is not a span.
    """
    categories = [category_of(p) for p in premises]
    result = category_of(conclusion)
    if result is None or any(c is None for c in categories):
        return None
    return CategoryRule(
        name=name,
        premises=tuple(c for c in categories if c is not None),
        conclusion=result,
    )

subterms

subterms(term: Term) -> Iterable[Term]

A ground term and every part of it.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

YIELDS DESCRIPTION
Term

Each subterm, the term first.

Source code in src/quivers/dsl/lexical/universe.py
def subterms(term: Term) -> Iterable[Term]:
    """A ground term and every part of it.

    Parameters
    ----------
    term : Term
        The term.

    Yields
    ------
    Term
        Each subterm, the term first.
    """
    yield term
    if isinstance(term, Node):
        for a in term.args:
            yield from subterms(a)

attested_categories

attested_categories(seeds: Iterable[Term], rules: Sequence[CategoryRule], bound: int) -> frozenset[Term]

The categories a grammar attests up to a depth bound.

PARAMETER DESCRIPTION
seeds

The categories of the monomorphic lexical entries.

TYPE: Iterable[Term]

rules

The deduction's rules on categories.

TYPE: Sequence[CategoryRule]

bound

The largest constructor depth of a derived category.

TYPE: int

RETURNS DESCRIPTION
frozenset[Term]

Every derived category and every part of one.

Source code in src/quivers/dsl/lexical/universe.py
def attested_categories(
    seeds: Iterable[Term], rules: Sequence[CategoryRule], bound: int
) -> frozenset[Term]:
    """The categories a grammar attests up to a depth bound.

    Parameters
    ----------
    seeds : Iterable[Term]
        The categories of the monomorphic lexical entries.
    rules : Sequence[CategoryRule]
        The deduction's rules on categories.
    bound : int
        The largest constructor depth of a derived category.

    Returns
    -------
    frozenset[Term]
        Every derived category and every part of one.
    """
    derived: set[Term] = {s for s in seeds if not variables_of(s)}
    changed = True
    while changed:
        changed = False
        snapshot = tuple(derived)
        for rule in rules:
            for found in _conclusions(rule, snapshot):
                if depth(found) <= bound and found not in derived:
                    derived.add(found)
                    changed = True
    return frozenset(part for category in derived for part in subterms(category))

entries

Lexicon entries after templates, polymorphism, and synthesis.

An Instance is one monomorphic lexical entry: a word, a ground category, a meaning, and the weights it reads. instances turns a deduction's written lexicon into instances. A template entry takes its template's category and its template's meaning at the entry's meaning. A polymorphic entry becomes one instance per assignment of category-set members to its variables: a variable over a finite set takes every member, and a variable over an infinite set takes the members the grammar attests up to the bound (the entry's bound, else the deduction's depth). Every instance of one entry reads one weight family, so the instances share their weight, unless the entry is per_instance: then each instance reads the entry's family at its instantiation (family_of_instance), a weight of its own. A meaning may name a category variable, which stands for its category as a term, and may call a meta computation on one, coord[X], which synthesizes the meaning from the variable's semantic type.

ENTRY_OPTIONS module-attribute

ENTRY_OPTIONS = frozenset({'learnable', 'shared', 'bound', 'instantiate', 'per_instance'})

The options a lexicon entry or a template may carry.

INSTANTIATIONS module-attribute

INSTANTIATIONS = ('bounded', 'lazy')

How a polymorphic entry is instantiated.

Instance didactic-model

Instance(*, word: str, category: Term, meaning: LetExprNode, learnable: bool = False, weights: tuple[str, ...] = (), apart: bool = False, source: int = 0, lazy: bool = False, line: int = 0, col: int = 0)

Bases: Model

One monomorphic lexicon entry.

PARAMETER DESCRIPTION
word

The word.

TYPE: str

category

The ground category.

TYPE: Term

meaning

The meaning.

TYPE: LetExprNode

learnable

Whether the instance has a learned weight of its own.

TYPE: bool DEFAULT: False

weights

The weight families it reads.

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

apart

Whether its entry weighs each instance apart (per_instance): its weight family is the entry's family at its instantiation.

TYPE: bool DEFAULT: False

source

The index of the written entry it comes from.

TYPE: int DEFAULT: 0

lazy

Whether its entry is instantiated lazily.

TYPE: bool DEFAULT: False

line

The written entry's line.

TYPE: int DEFAULT: 0

col

The written entry's column.

TYPE: int DEFAULT: 0

entry

entry() -> LexiconEntry

The instance as a plain lexicon entry.

RETURNS DESCRIPTION
LexiconEntry

The entry, with no option but learnable.

RAISES DESCRIPTION
LexicalError

If the category cannot be written as a category.

Source code in src/quivers/dsl/lexical/entries.py
def entry(self) -> LexiconEntry:
    """The instance as a plain lexicon entry.

    Returns
    -------
    LexiconEntry
        The entry, with no option but ``learnable``.

    Raises
    ------
    LexicalError
        If the category cannot be written as a category.
    """
    return LexiconEntry(
        words=(self.word,),
        category=LexiconCategoryFixed(
            category=to_object(self.category, self.line, self.col)
        ),
        lf=self.meaning,
        options=(
            (OptionEntry(key="learnable", value=OptionFlag()),)
            if self.learnable
            else ()
        ),
        line=self.line,
        col=self.col,
        weights=self.weights,
    )

Schema didactic-model

Schema(*, words: tuple[str, ...], binders: tuple[CategoryBinder, ...], category: Term, meaning: LetExprNode, options: tuple[OptionEntry, ...] = (), index: int = 0, line: int = 0, col: int = 0)

Bases: Model

A written entry read as a schema: binders, category, meaning, options.

PARAMETER DESCRIPTION
words

Its words.

TYPE: tuple[str, ...]

binders

Its category variables and their sets.

TYPE: tuple[CategoryBinder, ...]

category

Its category, over the variables.

TYPE: Term

meaning

Its meaning.

TYPE: LetExprNode

options

Its options, template options first.

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

index

Its position in the lexicon.

TYPE: int DEFAULT: 0

line

Its line.

TYPE: int DEFAULT: 0

col

Its column.

TYPE: int DEFAULT: 0

family_of_entry

family_of_entry(index: int) -> str

The weight family every instance of a written entry reads.

PARAMETER DESCRIPTION
index

The entry's position in the lexicon.

TYPE: int

RETURNS DESCRIPTION
str

__lexical_entry_<index>, a hidden name no written family uses.

Source code in src/quivers/dsl/lexical/entries.py
def family_of_entry(index: int) -> str:
    """The weight family every instance of a written entry reads.

    Parameters
    ----------
    index : int
        The entry's position in the lexicon.

    Returns
    -------
    str
        ``__lexical_entry_<index>``, a hidden name no written family uses.
    """
    return f"__lexical_entry_{index}"

family_of_instance

family_of_instance(index: int, assignment: Sequence[Term]) -> str

The weight family an instance of a per_instance entry reads.

The entry's family is indexed by the instantiation, as a rule schema's #[shared = F(n)] is by its parameters, so each assignment of categories to the entry's variables has a weight of its own, read by the instance however the entry is instantiated.

PARAMETER DESCRIPTION
index

The entry's position in the lexicon.

TYPE: int

assignment

The categories its variables take, in binder order.

TYPE: Sequence[Term]

RETURNS DESCRIPTION
str

__lexical_entry_<index>[c1,c2,...], the entry's hidden family at the rendered categories.

Source code in src/quivers/dsl/lexical/entries.py
def family_of_instance(index: int, assignment: Sequence[Term]) -> str:
    """The weight family an instance of a ``per_instance`` entry reads.

    The entry's family is indexed by the instantiation, as a rule schema's
    ``#[shared = F(n)]`` is by its parameters, so each assignment of
    categories to the entry's variables has a weight of its own, read by
    the instance however the entry is instantiated.

    Parameters
    ----------
    index : int
        The entry's position in the lexicon.
    assignment : Sequence[Term]
        The categories its variables take, in binder order.

    Returns
    -------
    str
        ``__lexical_entry_<index>[c1,c2,...]``, the entry's hidden family at
        the rendered categories.
    """
    return f"{family_of_entry(index)}[{','.join(render(c) for c in assignment)}]"

schemas

schemas(declaration: DeductionDecl, is_atom: Callable[[str], bool], templates: Mapping[str, LexicalTemplate], owner: str) -> tuple[Schema, ...]

Read each written entry as a schema, applying templates.

PARAMETER DESCRIPTION
declaration

The deduction.

TYPE: DeductionDecl

is_atom

Whether a name is one of its atoms.

TYPE: Callable[[str], bool]

templates

Its templates, by name.

TYPE: Mapping[str, LexicalTemplate]

owner

The deduction, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
tuple[Schema, ...]

One schema per written entry, in order.

RAISES DESCRIPTION
LexicalError

If an entry has an unknown option, or a latent (* or set of atoms) category with category variables or a template.

Source code in src/quivers/dsl/lexical/entries.py
def schemas(
    declaration: DeductionDecl,
    is_atom: Callable[[str], bool],
    templates: Mapping[str, LexicalTemplate],
    owner: str,
) -> tuple[Schema, ...]:
    """Read each written entry as a schema, applying templates.

    Parameters
    ----------
    declaration : DeductionDecl
        The deduction.
    is_atom : Callable[[str], bool]
        Whether a name is one of its atoms.
    templates : Mapping[str, LexicalTemplate]
        Its templates, by name.
    owner : str
        The deduction, for diagnostics.

    Returns
    -------
    tuple[Schema, ...]
        One schema per written entry, in order.

    Raises
    ------
    LexicalError
        If an entry has an unknown option, or a latent (``*`` or set of
        atoms) category with category variables or a template.
    """
    read: list[Schema] = []
    for index, entry in enumerate(declaration.lexicon):
        where = f"{owner}: lexicon entry {', '.join(repr(w) for w in entry.words)}"
        _check_options(entry.options, where, entry.line, entry.col)
        category = entry.category
        if isinstance(category, LexiconCategoryPolymorphic):
            binders = category.binders
            written = category.category
        elif isinstance(category, LexiconCategoryFixed):
            binders = ()
            written = category.category
        else:
            raise LexicalError(
                f"{where}: a latent category (`*` or a set of atoms) is not "
                "expanded with templates, category sets, or lexical rules; give "
                "the entry a category",
                entry.line,
                entry.col,
            )
        bound = frozenset(b.name for b in binders)
        template = _template_named(written, templates, is_atom)
        if template is not None:
            if binders:
                raise LexicalError(
                    f"{where}: names the template {template.name!r}, whose "
                    "category variables are its own",
                    entry.line,
                    entry.col,
                )
            _check_options(template.options, where, template.line, template.col)
            meaning = _apply_template(template, entry.lf)
            read.append(
                Schema(
                    words=entry.words,
                    binders=template.binders,
                    category=from_object(
                        template.category,
                        lambda name, b=frozenset(x.name for x in template.binders): (
                            name not in b and is_atom(name)
                        ),
                        owner=where,
                    ),
                    meaning=meaning,
                    options=(*template.options, *entry.options),
                    index=index,
                    line=entry.line,
                    col=entry.col,
                )
            )
            continue
        read.append(
            Schema(
                words=entry.words,
                binders=binders,
                category=from_object(
                    written,
                    lambda name, b=bound: name not in b and is_atom(name),
                    owner=where,
                ),
                meaning=entry.lf,
                options=entry.options,
                index=index,
                line=entry.line,
                col=entry.col,
            )
        )
    return tuple(read)

instances

instances(schema: Schema, sets: CategorySets, attested: Callable[[int], frozenset[Term]], synthesize: Callable[[str, Term, str, int, int], LetExprNode], *, depth_bound: int | None, owner: str) -> tuple[Instance, ...]

The instances of one schema.

PARAMETER DESCRIPTION
schema

The entry.

TYPE: Schema

sets

The deduction's category sets.

TYPE: CategorySets

attested

The categories the grammar attests up to a depth bound.

TYPE: Callable[[int], frozenset[Term]]

synthesize

Synthesizes a meaning: synthesize(generator, category, owner, line, col) runs the meta computation generator at the semantic type of category.

TYPE: Callable[[str, Term, str, int, int], LetExprNode]

depth_bound

The deduction's depth, if declared.

TYPE: int | None

owner

The deduction, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
tuple[Instance, ...]

One instance per word and assignment, in order.

RAISES DESCRIPTION
LexicalError

If a variable ranges over an undeclared set, over an infinite set with no bound, the category mentions a name that is neither an atom nor a variable, or the meaning uses a variable in a way no category spells.

Source code in src/quivers/dsl/lexical/entries.py
def instances(
    schema: Schema,
    sets: CategorySets,
    attested: Callable[[int], frozenset[Term]],
    synthesize: Callable[[str, Term, str, int, int], LetExprNode],
    *,
    depth_bound: int | None,
    owner: str,
) -> tuple[Instance, ...]:
    """The instances of one schema.

    Parameters
    ----------
    schema : Schema
        The entry.
    sets : CategorySets
        The deduction's category sets.
    attested : Callable[[int], frozenset[Term]]
        The categories the grammar attests up to a depth bound.
    synthesize : Callable[[str, Term, str, int, int], LetExprNode]
        Synthesizes a meaning: ``synthesize(generator, category, owner,
        line, col)`` runs the meta computation ``generator`` at the semantic
        type of ``category``.
    depth_bound : int | None
        The deduction's ``depth``, if declared.
    owner : str
        The deduction, for diagnostics.

    Returns
    -------
    tuple[Instance, ...]
        One instance per word and assignment, in order.

    Raises
    ------
    LexicalError
        If a variable ranges over an undeclared set, over an infinite set
        with no bound, the category mentions a name that is neither an atom
        nor a variable, or the meaning uses a variable in a way no category
        spells.
    """
    where = f"{owner}: lexicon entry {', '.join(repr(w) for w in schema.words)}"
    names = [b.name for b in schema.binders]
    if len(set(names)) != len(names):
        raise LexicalError(
            f"{where}: binds a category variable twice", schema.line, schema.col
        )
    free = [v for v in variables_of(schema.category) if v not in names]
    if free:
        raise LexicalError(
            f"{where}: its category names {free[0]!r}, which is neither an atom nor "
            "a variable its ∀ binds",
            schema.line,
            schema.col,
        )
    learnable = _flag(schema.options, "learnable")
    apart = _flag(schema.options, "per_instance")
    shared = _name(schema.options, "shared", where, schema.line, schema.col)
    if apart and shared:
        raise LexicalError(
            f"{where}: per_instance gives each instance a weight of its own, and "
            "shared one family for all; drop one of the two",
            schema.line,
            schema.col,
        )
    mode = _name(schema.options, "instantiate", where, schema.line, schema.col)
    if mode and mode not in INSTANTIATIONS:
        raise LexicalError(
            f"{where}: instantiate is {' or '.join(INSTANTIATIONS)}, not {mode!r}",
            schema.line,
            schema.col,
        )
    if mode and not schema.binders:
        raise LexicalError(
            f"{where}: instantiate applies to an entry with category variables",
            schema.line,
            schema.col,
        )
    bound = _number(schema.options, "bound", where, schema.line, schema.col)
    choices: list[tuple[Term, ...]] = []
    for binder in schema.binders:
        sets.require(binder.set_name, binder.line, binder.col)
        if binder.set_name in sets.finite:
            choices.append(sets.enumerate(binder.set_name))
            continue
        limit = bound if bound is not None else depth_bound
        if limit is None:
            raise LexicalError(
                f"{where}: {binder.name} ranges over {binder.set_name}, an infinite "
                "set, so its instances need a bound: give the entry #[bound=n] or "
                "the deduction a depth",
                binder.line,
                binder.col,
            )
        choices.append(
            tuple(
                sorted(
                    (
                        category
                        for category in attested(limit)
                        if depth(category) <= limit
                        and sets.contains(binder.set_name, category)
                    ),
                    key=render,
                )
            )
        )
    weights: tuple[str, ...] = ()
    own = learnable
    apart = apart and learnable
    if apart:
        own = False
    elif shared:
        weights = (shared,)
        own = False
    elif schema.binders and learnable:
        weights = (family_of_entry(schema.index),)
        own = False
    found: list[Instance] = []
    for assignment in product(*choices):
        mapping = dict(zip(names, assignment, strict=True))
        category = substitute(schema.category, mapping)
        meaning = _instantiate_meaning(schema.meaning, mapping, synthesize, where)
        for word in schema.words:
            found.append(
                Instance(
                    word=word,
                    category=category,
                    meaning=meaning,
                    learnable=own,
                    weights=(
                        (family_of_instance(schema.index, assignment),)
                        if apart
                        else weights
                    ),
                    apart=apart,
                    source=schema.index,
                    lazy=mode == "lazy",
                    line=schema.line,
                    col=schema.col,
                )
            )
    return tuple(found)

synthesis_calls

synthesis_calls(meaning: LetExprNode, variables: frozenset[str]) -> bool

Whether a meaning calls a meta computation on a category variable.

PARAMETER DESCRIPTION
meaning

The meaning.

TYPE: LetExprNode

variables

The category variables.

TYPE: frozenset[str]

RETURNS DESCRIPTION
bool

Whether some g[X] with X a variable occurs.

Source code in src/quivers/dsl/lexical/entries.py
def synthesis_calls(meaning: LetExprNode, variables: frozenset[str]) -> bool:
    """Whether a meaning calls a meta computation on a category variable.

    Parameters
    ----------
    meaning : LetExprNode
        The meaning.
    variables : frozenset[str]
        The category variables.

    Returns
    -------
    bool
        Whether some ``g[X]`` with ``X`` a variable occurs.
    """
    if isinstance(meaning, LetExprIndex):
        return _synthesis(meaning, variables) is not None or any(
            synthesis_calls(i, variables) for i in meaning.indices
        )
    if isinstance(meaning, LetExprCall):
        return any(synthesis_calls(a, variables) for a in meaning.args)
    return False

lexical_rules

Lexical rules: unary rules whose premise is a lexical item.

lexical rule r : span(I, J, NP, x) |- span(I, J, C, M) derives a lexical item from a lexical item over the same span. A rule in compile mode (the default) closes the lexicon when the deduction is expanded: each entry the premise matches yields a new entry, and entries derived this way are closed again, up to the rule's bound (one application by default). A rule in chart mode is a weighted unary rule over lexical items instead, applied to the lexicon's items and to the items the chart rules derive from them, up to the largest bound of the chart rules, and to nothing an ordinary rule derives; so the deduction is the one compile mode gives with the same bound. The deduction every reader sees has the entries it derives, each naming the rule (chart_lexicon); the agenda engine applies it in the chart (quivers.dsl.ast_nodes.plans), where a lexical item is wrapped as __lexical_item(C, __lexical_level_<d>), d the number of chart rule applications that derived it, the generated rule __lexical_lift unwraps it at any level, and the lexical rule has one copy per level below the bound, taking a wrapped item at its level to one at the next. Either way a learnable lexical rule has one learned weight, the family __lexical_rule_<r>: an entry it derives multiplies it into its source entry's weight, and every copy of the chart rule reads it.

RULE_OPTIONS module-attribute

RULE_OPTIONS = frozenset({'learnable', 'mode', 'bound'})

The options a lexical rule takes.

MODES module-attribute

MODES = ('compile', 'chart')

Where a lexical rule is applied.

WRAPPER module-attribute

WRAPPER = '__lexical_item'

The atom wrapping a lexical item's category when lexical rules run in the chart.

LEVEL module-attribute

LEVEL = '__lexical_level'

The prefix of the atoms counting the chart rule applications behind a lexical item.

LIFT module-attribute

LIFT = '__lexical_lift'

The generated rule that unwraps a lexical item.

ReadRule

ReadRule(rule: LexicalRuleDecl, is_atom: Callable[[str], bool], owner: str)

A lexical rule read as terms.

PARAMETER DESCRIPTION
rule

The rule.

TYPE: LexicalRuleDecl

is_atom

Whether a name is an atom.

TYPE: Callable[[str], bool]

owner

The deduction, for diagnostics.

TYPE: str

RAISES DESCRIPTION
LexicalError

If an option is unknown or malformed, an item is not a span, the premise's positions are not variables, or the conclusion's span is not the premise's.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def __init__(
    self, rule: LexicalRuleDecl, is_atom: Callable[[str], bool], owner: str
) -> None:
    self.rule = rule
    where = f"{owner}: lexical rule {rule.name!r}"
    self.where = where
    self.learnable = False
    self.mode = "compile"
    self.bound = 1
    for option in rule.options:
        if option.key not in RULE_OPTIONS:
            raise LexicalError(
                f"{where}: unknown option {option.key!r} (a lexical rule takes "
                f"{', '.join(sorted(RULE_OPTIONS))})",
                option.line or rule.line,
                option.col or rule.col,
            )
        if option.key == "learnable":
            self.learnable = True
        elif option.key == "mode":
            if (
                not isinstance(option.value, OptionName)
                or option.value.value not in MODES
            ):
                raise LexicalError(
                    f"{where}: mode is {' or '.join(MODES)}",
                    option.line or rule.line,
                    option.col or rule.col,
                )
            self.mode = option.value.value
        else:
            value = option.value
            if (
                not isinstance(value, OptionNumber)
                or not float(value.value).is_integer()
                or value.value < 1
            ):
                raise LexicalError(
                    f"{where}: bound takes a positive integer",
                    option.line or rule.line,
                    option.col or rule.col,
                )
            self.bound = int(value.value)
    self.premise = from_object(rule.premise, is_atom, owner=where)
    self.conclusion = from_object(rule.conclusion, is_atom, owner=where)
    for item in (self.premise, self.conclusion):
        if (
            not isinstance(item, Node)
            or item.head != SPAN_HEAD
            or len(item.args) not in (3, 4)
        ):
            raise LexicalError(
                f"{where}: relates two lexical items, span(i, j, category"
                f"[, meaning]), not {render(item)}",
                rule.line,
                rule.col,
            )
    assert isinstance(self.premise, Node) and isinstance(self.conclusion, Node)
    if len(self.premise.args) != len(self.conclusion.args):
        raise LexicalError(
            f"{where}: its premise and conclusion have different shapes",
            rule.line,
            rule.col,
        )
    start, stop = self.premise.args[0], self.premise.args[1]
    if not isinstance(start, Variable) or not isinstance(stop, Variable):
        raise LexicalError(
            f"{where}: its premise's positions are variables", rule.line, rule.col
        )
    if self.conclusion.args[:2] != (start, stop):
        raise LexicalError(
            f"{where}: keeps its item's span, so its conclusion's positions are "
            f"{start.name} and {stop.name}",
            rule.line,
            rule.col,
        )
    self.forms = len(self.premise.args) == 4

family property

family: tuple[str, ...]

The weight family the rule contributes, when it learns one.

RETURNS DESCRIPTION
tuple[str, ...]

(__lexical_rule_<r>,) or empty.

apply

apply(instance: Instance) -> Instance | None

The entry the rule derives from one entry, if its premise matches.

PARAMETER DESCRIPTION
instance

The entry.

TYPE: Instance

RETURNS DESCRIPTION
Instance | None

The derived entry, reading the entry's weights and the rule's.

RAISES DESCRIPTION
LexicalError

If the conclusion's category is not ground.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def apply(self, instance: Instance) -> Instance | None:
    """The entry the rule derives from one entry, if its premise matches.

    Parameters
    ----------
    instance : Instance
        The entry.

    Returns
    -------
    Instance | None
        The derived entry, reading the entry's weights and the rule's.

    Raises
    ------
    LexicalError
        If the conclusion's category is not ground.
    """
    assert isinstance(self.premise, Node) and isinstance(self.conclusion, Node)
    slots: list[Term] = [
        Variable(name="__start"),
        Variable(name="__stop"),
        instance.category,
    ]
    if self.forms:
        slots.append(from_meaning(instance.meaning, owner=self.where))
    bindings = match(
        self.premise, Node(head=SPAN_HEAD, args=tuple(slots), form="apply")
    )
    if bindings is None:
        return None
    category = substitute(self.conclusion.args[2], bindings)
    if variables_of(category):
        raise LexicalError(
            f"{self.where}: concludes with {render(category)}, whose "
            f"{variables_of(category)[0]} no premise binds",
            self.rule.line,
            self.rule.col,
        )
    meaning = instance.meaning
    if self.forms:
        meaning = to_meaning(
            substitute(self.conclusion.args[3], bindings),
            instance.line,
            instance.col,
        )
    return Instance(
        word=instance.word,
        category=category,
        meaning=meaning,
        learnable=False,
        weights=(*instance.weights, *self.family),
        source=instance.source,
        lazy=False,
        line=instance.line,
        col=instance.col,
    )

level

level(depth: int) -> str

The atom marking a lexical item a number of chart rule applications derived.

PARAMETER DESCRIPTION
depth

The number of applications.

TYPE: int

RETURNS DESCRIPTION
str

__lexical_level_<depth>, a hidden name.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def level(depth: int) -> str:
    """The atom marking a lexical item a number of chart rule applications derived.

    Parameters
    ----------
    depth : int
        The number of applications.

    Returns
    -------
    str
        ``__lexical_level_<depth>``, a hidden name.
    """
    return f"{LEVEL}_{depth}"

wrapped

wrapped(category: Term, depth: int) -> Term

A lexical item's category as the chart's lexical rules read it.

PARAMETER DESCRIPTION
category

The category.

TYPE: Term

depth

The number of chart rule applications that derived the item.

TYPE: int

RETURNS DESCRIPTION
Term

__lexical_item(category, __lexical_level_<depth>).

Source code in src/quivers/dsl/lexical/lexical_rules.py
def wrapped(category: Term, depth: int) -> Term:
    """A lexical item's category as the chart's lexical rules read it.

    Parameters
    ----------
    category : Term
        The category.
    depth : int
        The number of chart rule applications that derived the item.

    Returns
    -------
    Term
        ``__lexical_item(category, __lexical_level_<depth>)``.
    """
    return Node(head=WRAPPER, args=(category, Node(head=level(depth))), form="apply")

chart_depth

chart_depth(rules: Sequence[ReadRule]) -> int

The number of chart rule applications a lexical item may have behind it.

PARAMETER DESCRIPTION
rules

The lexical rules in chart mode.

TYPE: Sequence[ReadRule]

RETURNS DESCRIPTION
int

Their largest bound, or zero for none.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def chart_depth(rules: Sequence[ReadRule]) -> int:
    """The number of chart rule applications a lexical item may have behind it.

    Parameters
    ----------
    rules : Sequence[ReadRule]
        The lexical rules in ``chart`` mode.

    Returns
    -------
    int
        Their largest ``bound``, or zero for none.
    """
    return max((rule.bound for rule in rules), default=0)

chart_atoms

chart_atoms(rules: Sequence[ReadRule]) -> tuple[str, ...]

The atoms the chart's lexical rules add to a deduction's plan.

PARAMETER DESCRIPTION
rules

The lexical rules in chart mode.

TYPE: Sequence[ReadRule]

RETURNS DESCRIPTION
tuple[str, ...]

The wrapper and one level atom per depth, or none without rules.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def chart_atoms(rules: Sequence[ReadRule]) -> tuple[str, ...]:
    """The atoms the chart's lexical rules add to a deduction's plan.

    Parameters
    ----------
    rules : Sequence[ReadRule]
        The lexical rules in ``chart`` mode.

    Returns
    -------
    tuple[str, ...]
        The wrapper and one level atom per depth, or none without rules.
    """
    if not rules:
        return ()
    return (WRAPPER, *(level(depth) for depth in range(chart_depth(rules) + 1)))

family_of_rule

family_of_rule(name: str) -> str

The weight family of a learnable lexical rule.

PARAMETER DESCRIPTION
name

The lexical rule.

TYPE: str

RETURNS DESCRIPTION
str

__lexical_rule_<name>, a hidden name no written family uses.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def family_of_rule(name: str) -> str:
    """The weight family of a learnable lexical rule.

    Parameters
    ----------
    name : str
        The lexical rule.

    Returns
    -------
    str
        ``__lexical_rule_<name>``, a hidden name no written family uses.
    """
    return f"__lexical_rule_{name}"

compile_lexical_rules

compile_lexical_rules(found: Sequence[Instance], rules: Sequence[ReadRule]) -> tuple[Instance, ...]

Close a lexicon under its compiled lexical rules.

Every entry first reads its own weight as the family of its written entry, so an entry a rule derives reads the same weight.

PARAMETER DESCRIPTION
found

The lexicon's entries.

TYPE: Sequence[Instance]

rules

The lexical rules in compile mode.

TYPE: Sequence[ReadRule]

RETURNS DESCRIPTION
tuple[Instance, ...]

The entries, then the derived ones, chain by chain up to the largest bound.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def compile_lexical_rules(
    found: Sequence[Instance], rules: Sequence[ReadRule]
) -> tuple[Instance, ...]:
    """Close a lexicon under its compiled lexical rules.

    Every entry first reads its own weight as the family of its written
    entry, so an entry a rule derives reads the same weight.

    Parameters
    ----------
    found : Sequence[Instance]
        The lexicon's entries.
    rules : Sequence[ReadRule]
        The lexical rules in ``compile`` mode.

    Returns
    -------
    tuple[Instance, ...]
        The entries, then the derived ones, chain by chain up to the
        largest ``bound``.
    """
    if not rules:
        return tuple(found)
    entries = list(share_weights(found))
    frontier = list(entries)
    for _ in range(max(rule.bound for rule in rules)):
        derived: list[Instance] = []
        for instance in frontier:
            for rule in rules:
                result = rule.apply(instance)
                if result is not None:
                    derived.append(result)
        entries.extend(derived)
        frontier = derived
        if not frontier:
            break
    return tuple(entries)

share_weights

share_weights(found: Sequence[Instance]) -> tuple[Instance, ...]

Give every entry with a learned weight of its own its written entry's family.

An entry a lexical rule derives reads its source entry's weight, so the source's own weight becomes the family of its written entry, which both read.

PARAMETER DESCRIPTION
found

The lexicon's entries.

TYPE: Sequence[Instance]

RETURNS DESCRIPTION
tuple[Instance, ...]

The entries, each learnable one reading its written entry's family instead of a weight of its own.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def share_weights(found: Sequence[Instance]) -> tuple[Instance, ...]:
    """Give every entry with a learned weight of its own its written entry's family.

    An entry a lexical rule derives reads its source entry's weight, so the
    source's own weight becomes the family of its written entry, which both
    read.

    Parameters
    ----------
    found : Sequence[Instance]
        The lexicon's entries.

    Returns
    -------
    tuple[Instance, ...]
        The entries, each learnable one reading its written entry's family
        instead of a weight of its own.
    """
    return tuple(
        instance.with_(
            learnable=False,
            weights=(*instance.weights, family_of_entry(instance.source)),
        )
        if instance.learnable
        else instance
        for instance in found
    )

chart_lexicon

chart_lexicon(found: Sequence[Instance], rules: Sequence[ReadRule]) -> tuple[tuple[Instance, str], ...]

The entries lexical rules in chart mode derive from a lexicon.

The chart rules close the lexicon as compiled rules do: each round applies every rule to the entries the previous round derived, up to the rules' largest bound.

PARAMETER DESCRIPTION
found

The lexicon's entries, their weights shared (share_weights).

TYPE: Sequence[Instance]

rules

The lexical rules in chart mode.

TYPE: Sequence[ReadRule]

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

Each derived entry, reading its source's weights and the rule's, and the rule deriving it, chain by chain.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def chart_lexicon(
    found: Sequence[Instance], rules: Sequence[ReadRule]
) -> tuple[tuple[Instance, str], ...]:
    """The entries lexical rules in chart mode derive from a lexicon.

    The chart rules close the lexicon as compiled rules do: each round
    applies every rule to the entries the previous round derived, up to the
    rules' largest ``bound``.

    Parameters
    ----------
    found : Sequence[Instance]
        The lexicon's entries, their weights shared (`share_weights`).
    rules : Sequence[ReadRule]
        The lexical rules in ``chart`` mode.

    Returns
    -------
    tuple[tuple[Instance, str], ...]
        Each derived entry, reading its source's weights and the rule's,
        and the rule deriving it, chain by chain.
    """
    derived: list[tuple[Instance, str]] = []
    frontier = list(found)
    for _ in range(chart_depth(rules)):
        step = [
            (result, rule.rule.name)
            for instance in frontier
            for rule in rules
            if (result := rule.apply(instance)) is not None
        ]
        derived.extend(step)
        frontier = [instance for instance, _ in step]
        if not frontier:
            break
    return tuple(derived)

level_rule

level_rule(name: str, depth: int) -> str

The plan's copy of a chart lexical rule taking items at one level.

PARAMETER DESCRIPTION
name

The lexical rule.

TYPE: str

depth

The level of the items the copy takes.

TYPE: int

RETURNS DESCRIPTION
str

<name>__level<depth>.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def level_rule(name: str, depth: int) -> str:
    """The plan's copy of a chart lexical rule taking items at one level.

    Parameters
    ----------
    name : str
        The lexical rule.
    depth : int
        The level of the items the copy takes.

    Returns
    -------
    str
        ``<name>__level<depth>``.
    """
    return f"{name}__level{depth}"

chart_rules

chart_rules(rules: Sequence[ReadRule]) -> tuple[SequentRule, ...]

The chart rules lexical rules in chart mode become.

PARAMETER DESCRIPTION
rules

The lexical rules in chart mode.

TYPE: Sequence[ReadRule]

RETURNS DESCRIPTION
tuple[SequentRule, ...]

__lexical_lift, which unwraps a lexical item at any level, and one copy of each lexical rule per level below the largest bound, taking a wrapped item at its level to one at the next.

Source code in src/quivers/dsl/lexical/lexical_rules.py
def chart_rules(rules: Sequence[ReadRule]) -> tuple[SequentRule, ...]:
    """The chart rules lexical rules in ``chart`` mode become.

    Parameters
    ----------
    rules : Sequence[ReadRule]
        The lexical rules in ``chart`` mode.

    Returns
    -------
    tuple[SequentRule, ...]
        ``__lexical_lift``, which unwraps a lexical item at any level, and
        one copy of each lexical rule per level below the largest bound,
        taking a wrapped item at its level to one at the next.
    """
    forms = any(rule.forms for rule in rules)
    variables: list[Term] = [
        Variable(name="I"),
        Variable(name="J"),
        Node(head=WRAPPER, args=(Variable(name="X"), Variable(name="L")), form="apply"),
    ]
    if forms:
        variables.append(Variable(name="F"))
    lift_conclusion: list[Term] = [
        Variable(name="I"),
        Variable(name="J"),
        Variable(name="X"),
    ]
    if forms:
        lift_conclusion.append(Variable(name="F"))
    generated = [
        SequentRule(
            name=LIFT,
            premises=(
                to_object(Node(head=SPAN_HEAD, args=tuple(variables), form="apply")),
            ),
            conclusion=to_object(
                Node(head=SPAN_HEAD, args=tuple(lift_conclusion), form="apply")
            ),
        )
    ]
    for depth in range(chart_depth(rules)):
        for rule in rules:
            premise, conclusion = rule.premise, rule.conclusion
            assert isinstance(premise, Node) and isinstance(conclusion, Node)
            generated.append(
                SequentRule(
                    name=level_rule(rule.rule.name, depth),
                    premises=(
                        to_object(
                            _at_level(premise, depth), rule.rule.line, rule.rule.col
                        ),
                    ),
                    conclusion=to_object(
                        _at_level(conclusion, depth + 1), rule.rule.line, rule.rule.col
                    ),
                    line=rule.rule.line,
                    col=rule.rule.col,
                    options=(
                        (
                            OptionEntry(
                                key="shared",
                                value=OptionName(value=family_of_rule(rule.rule.name)),
                            ),
                        )
                        if rule.learnable
                        else ()
                    ),
                )
            )
    return tuple(generated)

wrap

wrap(instance: Instance) -> Instance

A lexical entry whose item lexical rules in the chart apply to.

PARAMETER DESCRIPTION
instance

The entry.

TYPE: Instance

RETURNS DESCRIPTION
Instance

The entry with its category wrapped at level zero, __lexical_item(C, __lexical_level_0).

Source code in src/quivers/dsl/lexical/lexical_rules.py
def wrap(instance: Instance) -> Instance:
    """A lexical entry whose item lexical rules in the chart apply to.

    Parameters
    ----------
    instance : Instance
        The entry.

    Returns
    -------
    Instance
        The entry with its category wrapped at level zero,
        ``__lexical_item(C, __lexical_level_0)``.
    """
    return instance.with_(category=wrapped(instance.category, 0))

lazy

Lazy instantiation: a polymorphic entry instantiated where a rule uses it.

Lazy instantiation is how the agenda engine runs a deduction, not a change to the deduction: the deduction every other reader sees (the checked elaboration, its item family, deriving, proofs, and every transpile target) has each instance of the entry as an entry of its lexicon. The agenda engine runs an agenda plan (quivers.dsl.ast_nodes.plans) instead, in which a lazily instantiated entry contributes, for each meaning its instances have, one item per token whose category __lazy_<k>_<m> stands for the entry with its category variables unbound and whose meaning is the instances' meaning. No instance of the entry is an axiom of that chart. Instead each rule premise whose category unifies with an instance's category is specialized: the specialized rule takes the placeholder item in that position, keeps the premise's meaning pattern, and instantiates its other premises and its conclusion by the unifier, so the variable is instantiated by the items the rule meets in the chart, and an instance enters the chart only as part of what a rule derives from it. The meaning is never written into a rule, so it may hold binders. A specialized rule reads its source rule's learned weight on the source's own bindings, so lazy and bounded instantiation give every derived item the same weight. An entry that weighs each instance apart (per_instance) has a placeholder that weighs nothing, and a rule specialized to it also reads the consumed instance's own weight (SpecializedWeight.entries), the one weight the instance's axiom carries under bounded instantiation. Every item and application the run hands out is read back through the plan's reveal, which maps a placeholder to the instances it stands for and a specialized application to its source rule's.

A specialized rule carries neither its source's guard nor its computed weight (OPERATION_OPTIONS), whose signatures are the source rule's telescope: the agenda engine runs the source rule's, read through the plan's record of the rule's source, on the specialized rule's bindings and the variables the specialization fixed.

A premise whose category is a variable nothing else constrains, or a premise that is a bare variable, unifies with every instance, so it is specialized to each, which is bounded instantiation for that rule alone. Such a premise would also match the placeholder item itself, which stands for every instance at once and is none of them; the agenda engine gives no premise of a rule an item the plan generates unless the premise was specialized to take it (quivers.dsl.compiler.deductions). A bare premise binds a whole item, which a specialized rule has to spell; where a term of the rule also holds the variable, the spelled item would hold its chart positions as terms, so that rule is refused.

OPERATION_OPTIONS module-attribute

OPERATION_OPTIONS = frozenset({'guard', 'weight'})

Rule options naming a computation over the rule's matched variables, which a specialized rule reads from its source rather than carrying.

Specialization didactic-model

Specialization(*, placeholders: tuple[Instance, ...] = (), rules: tuple[SequentRule, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), instances: Mapping[str, Mapping[int, Term]] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), names: tuple[str, ...] = (), consumed: Mapping[str, tuple[tuple[str, str, Term], ...]] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

What lazy instantiation adds to a deduction.

PARAMETER DESCRIPTION
placeholders

One entry per word and meaning of each lazy entry, its category the placeholder atom and its meaning the instances' meaning.

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

rules

The specialized rules.

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

instances

Each specialized rule's instance category at each position that takes a placeholder, for reading a derivation back as one over the instances.

TYPE: Mapping[str, Mapping[int, Term]] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE)

names

The placeholder atom of each lazy instance, in the order given.

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

consumed

Each specialized rule's consumed instances, in premise order: the placeholder, the word, and the instance category.

TYPE: Mapping[str, tuple[tuple[str, str, Term], ...]] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE)

placeholder

placeholder(source: int, meaning_class: int) -> str

The atom standing for a lazily instantiated entry at one meaning.

PARAMETER DESCRIPTION
source

The entry's position in the lexicon.

TYPE: int

meaning_class

The position of the meaning (and the weights) among the entry's.

TYPE: int

RETURNS DESCRIPTION
str

__lazy_<source>_<meaning_class>, a hidden name.

Source code in src/quivers/dsl/lexical/lazy.py
def placeholder(source: int, meaning_class: int) -> str:
    """The atom standing for a lazily instantiated entry at one meaning.

    Parameters
    ----------
    source : int
        The entry's position in the lexicon.
    meaning_class : int
        The position of the meaning (and the weights) among the entry's.

    Returns
    -------
    str
        ``__lazy_<source>_<meaning_class>``, a hidden name.
    """
    return f"__lazy_{source}_{meaning_class}"

specialize

specialize(lazy: Sequence[Instance], rules: Sequence[SequentRule], is_atom: Callable[[str], bool], owner: str, *, wrap: Callable[[Term], Term] | None = None, suffix: str = 'lazy', per_word: bool = False) -> Specialization

The placeholder entries and specialized rules of lazy entries.

PARAMETER DESCRIPTION
lazy

The instances of every lazily instantiated entry.

TYPE: Sequence[Instance]

rules

The rules to specialize.

TYPE: Sequence[SequentRule]

is_atom

Whether a name is an atom.

TYPE: Callable[[str], bool]

owner

The deduction, for diagnostics.

TYPE: str

wrap

Wraps a lexical item's category when the rules take wrapped items (lexical rules in the chart), or None.

TYPE: Callable[[Term], Term] | None DEFAULT: None

suffix

What a specialized rule's name adds to its source's.

TYPE: str DEFAULT: 'lazy'

per_word

Whether each word of an entry has a placeholder of its own, so a rule that consumes one knows the word: a grammar normalized per left-hand side reads the consumed instance's production, which is the word's.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Specialization

The placeholders, the specialized rules, and their instances.

RAISES DESCRIPTION
LexicalError

If a premise that is a bare variable would be specialized while the variable also occurs inside a term of the rule.

Source code in src/quivers/dsl/lexical/lazy.py
def specialize(
    lazy: Sequence[Instance],
    rules: Sequence[SequentRule],
    is_atom: Callable[[str], bool],
    owner: str,
    *,
    wrap: Callable[[Term], Term] | None = None,
    suffix: str = "lazy",
    per_word: bool = False,
) -> Specialization:
    """The placeholder entries and specialized rules of lazy entries.

    Parameters
    ----------
    lazy : Sequence[Instance]
        The instances of every lazily instantiated entry.
    rules : Sequence[SequentRule]
        The rules to specialize.
    is_atom : Callable[[str], bool]
        Whether a name is an atom.
    owner : str
        The deduction, for diagnostics.
    wrap : Callable[[Term], Term] | None
        Wraps a lexical item's category when the rules take wrapped items
        (lexical rules in the chart), or ``None``.
    suffix : str
        What a specialized rule's name adds to its source's.
    per_word : bool
        Whether each word of an entry has a placeholder of its own, so a
        rule that consumes one knows the word: a grammar normalized per
        left-hand side reads the consumed instance's production, which is
        the word's.

    Returns
    -------
    Specialization
        The placeholders, the specialized rules, and their instances.

    Raises
    ------
    LexicalError
        If a premise that is a bare variable would be specialized while
        the variable also occurs inside a term of the rule.
    """
    if not lazy:
        return Specialization()
    read = [
        (
            rule,
            tuple(
                from_object(p, is_atom, owner=f"{owner}: rule {rule.name!r}")
                for p in rule.premises
            ),
            from_object(rule.conclusion, is_atom, owner=f"{owner}: rule {rule.name!r}"),
        )
        for rule in rules
    ]
    classes: dict[tuple[int, str, tuple[str, ...], bool, bool, str], int] = {}
    placeholders: dict[tuple[str, str], Instance] = {}
    names: dict[int, str] = {}
    for position, instance in enumerate(lazy):
        where = f"{owner}: lexicon entry {instance.word!r}"
        meaning = render(from_meaning(instance.meaning, owner=where))
        # An entry that weighs each instance apart has one placeholder for
        # all of them, which weighs nothing: the rules specialized to it
        # read the consumed instance's weight.
        key = (
            instance.source,
            meaning,
            () if instance.apart else instance.weights,
            instance.learnable,
            instance.apart,
            instance.word if per_word else "",
        )
        if key not in classes:
            classes[key] = sum(1 for k in classes if k[0] == instance.source)
        name = placeholder(instance.source, classes[key])
        names[position] = name
        placeholders.setdefault(
            (name, instance.word),
            instance.with_(
                category=Node(head=name),
                weights=() if instance.apart else instance.weights,
            ),
        )
    # One item per placeholder and category: the words a placeholder
    # covers share its item, so a rule takes it once.
    items: list[tuple[Instance, str]] = []
    seen: set[tuple[str, str]] = set()
    for position, instance in enumerate(lazy):
        mark = (names[position], render(instance.category))
        if mark not in seen:
            seen.add(mark)
            items.append((instance, names[position]))
    specialized: list[SequentRule] = []
    instances: dict[str, dict[int, Term]] = {}
    consumed: dict[str, tuple[tuple[str, str, Term], ...]] = {}
    arity = _span_arity(read)
    for rule, premises, conclusion in read:
        assignments = _assignments(premises, items, wrap, arity)
        if not assignments:
            continue
        _check_whole_items(rule, premises, conclusion, assignments, owner)
        for number, (chosen, unifier) in enumerate(assignments):
            made = _specialized_rule(
                rule,
                premises,
                conclusion,
                chosen,
                unifier,
                f"{rule.name}__{suffix}{number}",
                wrap,
            )
            specialized.append(made)
            instances[made.name] = {
                index: instance.category for index, (instance, _) in chosen.items()
            }
            consumed[made.name] = tuple(
                (name, instance.word, instance.category)
                for _, (instance, name) in sorted(chosen.items())
            )
    return Specialization(
        placeholders=tuple(placeholders.values()),
        rules=tuple(specialized),
        instances=instances,
        names=tuple(names[position] for position in range(len(lazy))),
        consumed=consumed,
    )

features

Atoms with features: atoms NP[num : Num] and categories NP[sg].

A featured atom is a family of atoms, one per assignment of members of its feature sets, which must be finite sets of atoms: NP[sg] is the atom NP__sg, and the item family of the deduction has one constructor per such atom. A rule over feature variables (NP[n]) is one rule per assignment of the variables, named r__<value>...; each variable takes the members of every feature set it fills. Every occurrence of a featured atom carries its features, so a featured atom written bare is refused.

Features didactic-model

Features(*, sets: Mapping[str, tuple[str, ...]] = field(opaque=True, extras=OPAQUE_BY_VALUE), values: Mapping[str, tuple[tuple[str, ...], ...]] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The featured atoms of one deduction.

PARAMETER DESCRIPTION
sets

Each featured atom's feature sets, in order.

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

values

Each featured atom's admissible values at each feature.

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

atoms property

atoms: frozenset[str]

The featured atoms.

RETURNS DESCRIPTION
frozenset[str]

Their names.

instances

instances() -> dict[str, str]

Every atom the featured atoms stand for, with the atom it refines.

RETURNS DESCRIPTION
dict[str, str]

NP__sg to NP, for each assignment.

Source code in src/quivers/dsl/lexical/features.py
def instances(self) -> dict[str, str]:
    """Every atom the featured atoms stand for, with the atom it refines.

    Returns
    -------
    dict[str, str]
        ``NP__sg`` to ``NP``, for each assignment.
    """
    found: dict[str, str] = {}
    for atom, choices in self.values.items():
        for assignment in product(*choices):
            found[featured_name(atom, assignment)] = atom
    return found

ground

ground(term: Term, where: str, line: int, col: int) -> Term

Replace every featured atom of a ground term by its atom.

PARAMETER DESCRIPTION
term

A category or item.

TYPE: Term

where

Its owner, for diagnostics.

TYPE: str

line

Where it is written.

TYPE: int

col

Where it is written.

TYPE: int

RETURNS DESCRIPTION
Term

The term over plain atoms.

RAISES DESCRIPTION
LexicalError

If a featured atom is written bare, with the wrong number of features, or with a value outside its feature's set.

Source code in src/quivers/dsl/lexical/features.py
def ground(self, term: Term, where: str, line: int, col: int) -> Term:
    """Replace every featured atom of a ground term by its atom.

    Parameters
    ----------
    term : Term
        A category or item.
    where : str
        Its owner, for diagnostics.
    line : int
        Where it is written.
    col : int
        Where it is written.

    Returns
    -------
    Term
        The term over plain atoms.

    Raises
    ------
    LexicalError
        If a featured atom is written bare, with the wrong number of
        features, or with a value outside its feature's set.
    """
    if isinstance(term, Variable):
        return term
    assert isinstance(term, Node)
    if term.form == "features":
        if term.head not in self.sets:
            raise LexicalError(
                f"{where}: {term.head!r} is written with features, which its "
                "atoms line does not declare",
                line,
                col,
            )
        choices = self.values[term.head]
        if len(term.args) != len(choices):
            raise LexicalError(
                f"{where}: {term.head} takes {len(choices)} features, not "
                f"{len(term.args)}",
                line,
                col,
            )
        values: list[str] = []
        for value, allowed, set_name in zip(
            term.args, choices, self.sets[term.head], strict=True
        ):
            if (
                not isinstance(value, Node)
                or value.args
                or value.head not in allowed
            ):
                raise LexicalError(
                    f"{where}: {render(value)} is no member of {set_name}, the "
                    f"set of a feature of {term.head}",
                    line,
                    col,
                )
            values.append(value.head)
        return Node(head=featured_name(term.head, values))
    if not term.args and term.form == "atom" and term.head in self.sets:
        raise LexicalError(
            f"{where}: {term.head} has features, so it is written {term.head}[...]",
            line,
            col,
        )
    if not term.args:
        return term
    return term.with_(
        args=tuple(self.ground(a, where, line, col) for a in term.args)
    )

variables

variables(term: Term) -> dict[str, frozenset[str]]

The feature variables of a term and the values each may take.

PARAMETER DESCRIPTION
term

A rule's premise or conclusion.

TYPE: Term

RETURNS DESCRIPTION
dict[str, frozenset[str]]

Each variable filling a feature, with the values of every feature it fills.

Source code in src/quivers/dsl/lexical/features.py
def variables(self, term: Term) -> dict[str, frozenset[str]]:
    """The feature variables of a term and the values each may take.

    Parameters
    ----------
    term : Term
        A rule's premise or conclusion.

    Returns
    -------
    dict[str, frozenset[str]]
        Each variable filling a feature, with the values of every
        feature it fills.
    """
    found: dict[str, frozenset[str]] = {}

    def visit(t: Term) -> None:
        if not isinstance(t, Node):
            return
        if t.form == "features" and t.head in self.values:
            for value, allowed in zip(t.args, self.values[t.head], strict=False):
                if isinstance(value, Variable):
                    found[value.name] = found.get(
                        value.name, frozenset(allowed)
                    ) & frozenset(allowed)
        for a in t.args:
            visit(a)

    visit(term)
    return found

featured_name

featured_name(atom: str, values: Sequence[str]) -> str

The atom a featured atom is at some feature values.

PARAMETER DESCRIPTION
atom

The featured atom.

TYPE: str

values

Its feature values, in order.

TYPE: Sequence[str]

RETURNS DESCRIPTION
str

atom__value1__value2..., a hidden name.

Source code in src/quivers/dsl/lexical/features.py
def featured_name(atom: str, values: Sequence[str]) -> str:
    """The atom a featured atom is at some feature values.

    Parameters
    ----------
    atom : str
        The featured atom.
    values : Sequence[str]
        Its feature values, in order.

    Returns
    -------
    str
        ``atom__value1__value2...``, a hidden name.
    """
    return "__".join((atom, *values))

read_features

read_features(declared: Sequence[AtomFeatures], sets: CategorySets, owner: str) -> Features

Read a deduction's featured atoms.

PARAMETER DESCRIPTION
declared

The featured atoms of its atoms lines.

TYPE: Sequence[AtomFeatures]

sets

Its category sets.

TYPE: CategorySets

owner

The deduction, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
Features

The featured atoms.

RAISES DESCRIPTION
LexicalError

If a feature's set is undeclared, infinite, or has a member that is not an atom, or an atom is declared with features twice.

Source code in src/quivers/dsl/lexical/features.py
def read_features(
    declared: Sequence[AtomFeatures], sets: CategorySets, owner: str
) -> Features:
    """Read a deduction's featured atoms.

    Parameters
    ----------
    declared : Sequence[AtomFeatures]
        The featured atoms of its atoms lines.
    sets : CategorySets
        Its category sets.
    owner : str
        The deduction, for diagnostics.

    Returns
    -------
    Features
        The featured atoms.

    Raises
    ------
    LexicalError
        If a feature's set is undeclared, infinite, or has a member that is
        not an atom, or an atom is declared with features twice.
    """
    feature_sets: dict[str, tuple[str, ...]] = {}
    values: dict[str, tuple[tuple[str, ...], ...]] = {}
    for item in declared:
        if item.atom in feature_sets:
            raise LexicalError(
                f"{owner}: {item.atom} is declared with features twice",
                item.line,
                item.col,
            )
        choices: list[tuple[str, ...]] = []
        for feature in item.features:
            sets.require(feature.set_name, feature.line, feature.col)
            if feature.set_name not in sets.finite:
                raise LexicalError(
                    f"{owner}: feature {feature.name or feature.set_name} of "
                    f"{item.atom} ranges over {feature.set_name}, an infinite set; "
                    "a feature's values are finitely many atoms",
                    feature.line,
                    feature.col,
                )
            members = sets.enumerate(feature.set_name)
            for member in members:
                if not isinstance(member, Node) or member.args:
                    raise LexicalError(
                        f"{owner}: {render(member)} in {feature.set_name} is not an "
                        "atom; a feature's values are atoms",
                        feature.line,
                        feature.col,
                    )
            choices.append(tuple(m.head for m in members if isinstance(m, Node)))
        feature_sets[item.atom] = tuple(f.set_name for f in item.features)
        values[item.atom] = tuple(choices)
    return Features(sets=feature_sets, values=values)

instantiate_rules

instantiate_rules(rules: Sequence[SequentRule], features: Features, is_atom: Callable[[str], bool], owner: str) -> tuple[tuple[SequentRule, ...], dict[str, str]]

Each rule at every assignment of its feature variables.

PARAMETER DESCRIPTION
rules

The rules.

TYPE: Sequence[SequentRule]

features

The featured atoms.

TYPE: Features

is_atom

Whether a name is an atom.

TYPE: Callable[[str], bool]

owner

The deduction, for diagnostics.

TYPE: str

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

The rules over plain atoms, and each rule's source rule by name.

RAISES DESCRIPTION
LexicalError

If a featured atom is written bare or with values outside its sets, or a feature variable can take no value.

Source code in src/quivers/dsl/lexical/features.py
def instantiate_rules(
    rules: Sequence[SequentRule],
    features: Features,
    is_atom: Callable[[str], bool],
    owner: str,
) -> tuple[tuple[SequentRule, ...], dict[str, str]]:
    """Each rule at every assignment of its feature variables.

    Parameters
    ----------
    rules : Sequence[SequentRule]
        The rules.
    features : Features
        The featured atoms.
    is_atom : Callable[[str], bool]
        Whether a name is an atom.
    owner : str
        The deduction, for diagnostics.

    Returns
    -------
    tuple[tuple[SequentRule, ...], dict[str, str]]
        The rules over plain atoms, and each rule's source rule by name.

    Raises
    ------
    LexicalError
        If a featured atom is written bare or with values outside its
        sets, or a feature variable can take no value.
    """
    if not features.sets:
        return tuple(rules), {rule.name: rule.name for rule in rules}
    result: list[SequentRule] = []
    sources: dict[str, str] = {}
    for rule in rules:
        where = f"{owner}: rule {rule.name!r}"
        premises = [from_object(p, is_atom, owner=where) for p in rule.premises]
        conclusion = from_object(rule.conclusion, is_atom, owner=where)
        domains: dict[str, frozenset[str]] = {}
        for term in (*premises, conclusion):
            for name, allowed in features.variables(term).items():
                domains[name] = domains.get(name, allowed) & allowed
        empty = [name for name, allowed in domains.items() if not allowed]
        if empty:
            raise LexicalError(
                f"{where}: feature variable {empty[0]} fills features with no "
                "common value",
                rule.line,
                rule.col,
            )
        names = sorted(domains)
        for assignment in product(*(sorted(domains[n]) for n in names)):
            mapping: dict[str, Term] = {
                n: Node(head=v) for n, v in zip(names, assignment, strict=True)
            }
            name = "__".join((rule.name, *assignment)) if names else rule.name
            written = [
                features.ground(substitute(t, mapping), where, rule.line, rule.col)
                for t in premises
            ]
            concluded = features.ground(
                substitute(conclusion, mapping), where, rule.line, rule.col
            )
            result.append(
                rule.with_(
                    name=name,
                    premises=tuple(to_object(t, rule.line, rule.col) for t in written),
                    conclusion=to_object(concluded, rule.line, rule.col),
                )
            )
            sources[name] = rule.name
    return tuple(result), sources

semantics

Semantic types of categories, and the typing check of lexical meanings.

semantics Ty and its clauses S => T, Fwd(A, B) => Arr(B, A) give each category a semantic type by structural recursion: the first clause whose category pattern matches gives the type, with each pattern variable standing for the type of the category it matched. The types are terms of the syntax the judgment Ty(ctx, term, type) types; every meaning a deduction's lexicon assigns, written or synthesized, must have a derivation of Ty in the empty context at the semantic type of its category.

SemanticTypes

SemanticTypes(declaration: SemanticsDecl, is_atom: Callable[[str], bool], judgments: Mapping[str, JudgmentSystem], owner: str)

The semantic types of one deduction's categories.

PARAMETER DESCRIPTION
declaration

The semantics block.

TYPE: SemanticsDecl

is_atom

Whether a name is one of the deduction's atoms.

TYPE: Callable[[str], bool]

judgments

The module's judgments.

TYPE: Mapping[str, JudgmentSystem]

owner

The deduction, for diagnostics.

TYPE: str

RAISES DESCRIPTION
LexicalError

If the judgment is undeclared or is not Ty(ctx, term, type).

Source code in src/quivers/dsl/lexical/semantics.py
def __init__(
    self,
    declaration: SemanticsDecl,
    is_atom: Callable[[str], bool],
    judgments: Mapping[str, JudgmentSystem],
    owner: str,
) -> None:
    self.declaration = declaration
    self.owner = owner
    system = judgments.get(declaration.judgment)
    if system is None:
        raise LexicalError(
            f"{owner}: semantics names {declaration.judgment!r}, which is not a "
            "declared judgment",
            declaration.line,
            declaration.col,
        )
    form = system.forms[declaration.judgment]
    contexts = [a for a in form.arguments if a.context]
    if len(form.arguments) != 3 or len(contexts) != 1:
        raise LexicalError(
            f"{owner}: semantics checks meanings with "
            f"{declaration.judgment!r} as Ty(ctx, term, type)",
            declaration.line,
            declaration.col,
        )
    self.system = system
    self.clauses: list[tuple[Term, Term, surface.ObjectExpr]] = []
    for clause in declaration.clauses:
        pattern = from_object(
            clause.category,
            is_atom,
            owner=f"{owner}: semantic clause",
        )
        variables = _pattern_variables(pattern)
        type_term = from_object(
            clause.type_expr,
            lambda name, bound=variables: name not in bound,
            owner=f"{owner}: semantic clause",
        )
        self.clauses.append((pattern, type_term, clause.category))

type_of

type_of(category: Term, line: int, col: int) -> Term

The semantic type of a ground category.

PARAMETER DESCRIPTION
category

The category.

TYPE: Term

line

Where it is used.

TYPE: int

col

Where it is used.

TYPE: int

RETURNS DESCRIPTION
Term

Its type, a ground term of the judgment's syntax.

RAISES DESCRIPTION
LexicalError

If no clause matches the category or one of its parts.

Source code in src/quivers/dsl/lexical/semantics.py
def type_of(self, category: Term, line: int, col: int) -> Term:
    """The semantic type of a ground category.

    Parameters
    ----------
    category : Term
        The category.
    line : int
        Where it is used.
    col : int
        Where it is used.

    Returns
    -------
    Term
        Its type, a ground term of the judgment's syntax.

    Raises
    ------
    LexicalError
        If no clause matches the category or one of its parts.
    """
    for pattern, type_term, _ in self.clauses:
        bindings = match(pattern, category)
        if bindings is None:
            continue
        types = {
            name: self.type_of(value, line, col) for name, value in bindings.items()
        }
        return substitute(type_term, types)
    raise LexicalError(
        f"{self.owner}: no semantics clause gives the type of category "
        f"{render(category)}",
        line,
        col,
    )

check

check(meaning: LetExprNode, category: Term, *, owner: str) -> None

Refuse a meaning without a typing at its category's type.

PARAMETER DESCRIPTION
meaning

The meaning.

TYPE: LetExprNode

category

Its category.

TYPE: Term

owner

The entry, for diagnostics.

TYPE: str

RAISES DESCRIPTION
LexicalError

If the meaning is not a term of the judgment's syntax, or has no derivation of the judgment at the category's type; the message names the type and the constraint that failed.

Source code in src/quivers/dsl/lexical/semantics.py
def check(
    self, meaning: surface.LetExprNode, category: Term, *, owner: str
) -> None:
    """Refuse a meaning without a typing at its category's type.

    Parameters
    ----------
    meaning : LetExprNode
        The meaning.
    category : Term
        Its category.
    owner : str
        The entry, for diagnostics.

    Raises
    ------
    LexicalError
        If the meaning is not a term of the judgment's syntax, or has no
        derivation of the judgment at the category's type; the message
        names the type and the constraint that failed.
    """
    line = getattr(meaning, "line", 0)
    col = getattr(meaning, "col", 0)
    expected = self.type_of(category, line, col)
    signature = self.system.signature
    judgment = self.declaration.judgment
    try:
        term = logical_form(meaning, signature)
        if not isinstance(term, SyntaxTerm):
            raise JudgmentFailure("a meaning is a closed term")
        goal = self.system.goal(
            judgment,
            ContextValue(entries=()),
            term,
            from_term(to_syntax(expected, signature)),
        )
        self.system.derivations(goal, limit=1)
    except JudgmentFailure as error:
        raise LexicalError(
            f"{owner}: its meaning has no derivation of {judgment} at "
            f"{render(expected)}, the type of {render(category)}: {error}",
            line,
            col,
        ) from error

judgment_systems

judgment_systems(statements: Sequence[object]) -> dict[str, JudgmentSystem]

Build the judgment systems a module declares.

PARAMETER DESCRIPTION
statements

The module's statements.

TYPE: Sequence[object]

RETURNS DESCRIPTION
dict[str, JudgmentSystem]

Each judgment's system, by name.

RAISES DESCRIPTION
LexicalError

If a syntax or a judgment does not compile.

Source code in src/quivers/dsl/lexical/semantics.py
def judgment_systems(statements: Sequence[object]) -> dict[str, JudgmentSystem]:
    """Build the judgment systems a module declares.

    Parameters
    ----------
    statements : Sequence[object]
        The module's statements.

    Returns
    -------
    dict[str, JudgmentSystem]
        Each judgment's system, by name.

    Raises
    ------
    LexicalError
        If a syntax or a judgment does not compile.
    """
    signatures: dict[str, Signature] = {}
    judgments: list[surface.JudgmentDecl] = []
    for statement in statements:
        if isinstance(statement, surface.SyntaxDecl):
            try:
                signatures[statement.name] = _signature_from_declaration(statement)
            except CompileError as error:
                raise LexicalError(str(error), error.line, error.col) from error
        elif isinstance(statement, surface.JudgmentDecl):
            judgments.append(statement)
    try:
        return compile_judgments(judgments, signatures)
    except CompileError as error:
        raise LexicalError(str(error), error.line, error.col) from error

to_syntax

to_syntax(term: Term, signature: Signature) -> Term

A ground term as a term of a syntax.

PARAMETER DESCRIPTION
term

The term, over the syntax's constructors.

TYPE: Term

signature

The syntax.

TYPE: Signature

RETURNS DESCRIPTION
Term

The term.

RAISES DESCRIPTION
LexicalError

If the term has a variable or a head the syntax does not declare.

Source code in src/quivers/dsl/lexical/semantics.py
def to_syntax(term: Term, signature: Signature) -> SyntaxTerm:
    """A ground term as a term of a syntax.

    Parameters
    ----------
    term : Term
        The term, over the syntax's constructors.
    signature : Signature
        The syntax.

    Returns
    -------
    SyntaxTerm
        The term.

    Raises
    ------
    LexicalError
        If the term has a variable or a head the syntax does not declare.
    """
    if isinstance(term, Variable):
        raise LexicalError(f"semantic type {term.name!r} is not ground")
    assert isinstance(term, Node)
    if term.head not in signature.constructors:
        raise LexicalError(
            f"semantic type {render(term)} uses {term.head!r}, which is not a "
            f"constructor of syntax {signature.name!r}"
        )
    return SyntaxTerm(
        op=term.head, args=tuple(to_syntax(a, signature) for a in term.args)
    )

synthesis

Type-directed synthesis of lexical meanings by meta computations.

A polymorphic entry's meaning may call a meta computation on one of its category variables, coord[X]. At each instance the computation runs in the module's meta phase on the semantic type of the category X takes, quoted as a SynValue (a nullary type constructor E as ValueVar("E"), an applied one Arr(E, T) as ValueCall("Arr", ...)), and returns the meaning, quoted the same way. Generalized conjunction is the standard case: it recurs on the type [@partee1983generalized]. The synthesized meaning is checked by the deduction's typing judgment like a written one.

SYNTAX_VALUE module-attribute

SYNTAX_VALUE = 'SynValue'

The meta-phase family a synthesizer takes and returns.

SynthesisCall didactic-model

SynthesisCall(*, generator: str, argument: Term, owner: str, line: int = 0, col: int = 0)

Bases: Model

One meaning to synthesize.

PARAMETER DESCRIPTION
generator

The meta computation.

TYPE: str

argument

The semantic type it receives, a ground term.

TYPE: Term

owner

The entry the meaning is for, for diagnostics.

TYPE: str

line

The call's line.

TYPE: int DEFAULT: 0

col

The call's column.

TYPE: int DEFAULT: 0

synthesize

synthesize(module: Module, calls: Sequence[SynthesisCall], *, module_name: str, file_path: str) -> tuple[LetExprNode, ...]

Run each synthesis call in the module's meta phase.

PARAMETER DESCRIPTION
module

The module, whose meta declarations the calls may use.

TYPE: Module

calls

The calls, in order.

TYPE: Sequence[SynthesisCall]

module_name

The module's name.

TYPE: str

file_path

The path recorded on diagnostics.

TYPE: str

RETURNS DESCRIPTION
tuple[LetExprNode, ...]

Each call's meaning, in order.

RAISES DESCRIPTION
LexicalError

If a generator is not a meta computation from one SynValue to a SynValue, refuses, fails, or returns syntax that is not a meaning.

Source code in src/quivers/dsl/lexical/synthesis.py
def synthesize(
    module: Module,
    calls: Sequence[SynthesisCall],
    *,
    module_name: str,
    file_path: str,
) -> tuple[LetExprNode, ...]:
    """Run each synthesis call in the module's meta phase.

    Parameters
    ----------
    module : Module
        The module, whose meta declarations the calls may use.
    calls : Sequence[SynthesisCall]
        The calls, in order.
    module_name : str
        The module's name.
    file_path : str
        The path recorded on diagnostics.

    Returns
    -------
    tuple[LetExprNode, ...]
        Each call's meaning, in order.

    Raises
    ------
    LexicalError
        If a generator is not a meta computation from one `SynValue` to a
        `SynValue`, refuses, fails, or returns syntax that is not a meaning.
    """
    if not calls:
        return ()
    phase = meta_phase._MetaPhase(module, module_name=module_name, file_path=file_path)
    wrappers: dict[str, QiecComputationDecl] = {}
    for call in calls:
        if call.generator in wrappers:
            continue
        try:
            generator = phase._generator(call.generator, call.line, call.col)
        except QiecDiagnosticError as error:
            raise LexicalError(
                f"{call.owner}: {error.message}", call.line, call.col
            ) from error
        if (
            len(generator.parameters) != 1
            or not _is_syntax_value(generator.parameters[0].type_expr)
            or not _is_syntax_value(generator.result_type)
            or generator.binders
        ):
            raise LexicalError(
                f"{call.owner}: {call.generator!r} synthesizes a meaning, so it "
                f"takes one {SYNTAX_VALUE} (the semantic type) and returns a "
                f"{SYNTAX_VALUE}",
                call.line,
                call.col,
            )
        wrappers[call.generator] = _wrapper(phase, call)
    module_part = (
        *phase._phase_one_data(),
        *phase.meta_declarations,
        *wrappers.values(),
    )
    meta_module = Module(statements=(*phase._library_part(module_part), *module_part))
    try:
        checked = meta_phase._check_meta_module(meta_module, file_path=file_path)
    except QiecDiagnosticError as error:
        raise LexicalError(error.message, error.line or 0, error.column or 0) from error
    universe = MetaUniverse(checked)
    meanings: list[LetExprNode] = []
    for call in calls:
        wrapper = wrappers[call.generator]
        try:
            argument = _quote(universe, call.argument)
            value = phase._evaluate(
                checked,
                wrapper.name,
                (argument,),
                code=LexicalError.code,
                line=call.line,
                col=call.col,
            )
            value = phase._outcome(
                universe,
                wrapper.name,
                value,
                code=LexicalError.code,
                line=call.line,
                col=call.col,
                subject=f"{call.generator}[{render(call.argument)}]",
            )
            meanings.append(_meaning(universe, value, call.line, call.col))
        except QiecDiagnosticError as error:
            raise LexicalError(
                f"{call.owner}: synthesizing its meaning by {call.generator!r} at "
                f"{render(call.argument)} failed: {error.message}",
                call.line,
                call.col,
            ) from error
        except MetaValueError as error:
            raise LexicalError(
                f"{call.owner}: {call.generator!r} returned {error}",
                call.line,
                call.col,
            ) from error
    return tuple(meanings)

terms

Categories, items, and meanings as first-order terms.

A deduction writes its categories and items as object expressions (Fwd(S, NP), S \ NP, span(I, J, X, F)) and its lexical meanings as let expressions (Lam(x, App(dog, x))). Expansion reasons about both as first-order terms over the deduction's atoms: a name that is not an atom is a variable. This module converts between the source forms and Term, and implements the operations expansion needs on terms: substitution, matching, unification, depth, and renaming.

Term didactic-model

Term()

Bases: TaggedUnion

A first-order term over a deduction's atoms.

Variable didactic-model

Variable(*, name: str, kind: Literal['variable'] = 'variable')

Bases: Term

A variable.

PARAMETER DESCRIPTION
name

The variable's name.

TYPE: str

Node didactic-model

Node(*, head: str, args: tuple[Term, ...] = (), form: Literal['atom', 'apply', 'slash', 'features', 'integer', 'string'] = 'atom', kind: Literal['node'] = 'node')

Bases: Term

An atom, an application, a slash, or an atom at feature values.

PARAMETER DESCRIPTION
head

The atom, the applied symbol, the slash (/ or \), or the featured atom.

TYPE: str

args

The arguments; empty for an atom.

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

form

How the source spells it: atom, apply, slash, features, integer, or string.

TYPE: Literal['atom', 'apply', 'slash', 'features', 'integer', 'string'] DEFAULT: 'atom'

atom

atom(name: str) -> Node

The atom of a name.

PARAMETER DESCRIPTION
name

The atom.

TYPE: str

RETURNS DESCRIPTION
Node

The atom as a term.

Source code in src/quivers/dsl/lexical/terms.py
def atom(name: str) -> Node:
    """The atom of a name.

    Parameters
    ----------
    name : str
        The atom.

    Returns
    -------
    Node
        The atom as a term.
    """
    return Node(head=name)

apply

apply(head: str, *args: Term) -> Node

Apply a symbol.

PARAMETER DESCRIPTION
head

The symbol.

TYPE: str

*args

Its arguments.

TYPE: Term DEFAULT: ()

RETURNS DESCRIPTION
Node

The application.

Source code in src/quivers/dsl/lexical/terms.py
def apply(head: str, *args: Term) -> Node:
    """Apply a symbol.

    Parameters
    ----------
    head : str
        The symbol.
    *args : Term
        Its arguments.

    Returns
    -------
    Node
        The application.
    """
    return Node(head=head, args=args, form="apply")

from_object

from_object(expr: ObjectExpr, is_atom: Callable[[str], bool], *, owner: str) -> Term

Read an object expression as a term.

PARAMETER DESCRIPTION
expr

A category or an item.

TYPE: ObjectExpr

is_atom

Whether a bare name is an atom rather than a variable.

TYPE: Callable[[str], bool]

owner

What the expression belongs to, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
Term

The term.

RAISES DESCRIPTION
LexicalError

If the expression is not a category: a product, a coproduct, a space, or a schema spine.

Source code in src/quivers/dsl/lexical/terms.py
def from_object(
    expr: ObjectExpr, is_atom: Callable[[str], bool], *, owner: str
) -> Term:
    """Read an object expression as a term.

    Parameters
    ----------
    expr : ObjectExpr
        A category or an item.
    is_atom : Callable[[str], bool]
        Whether a bare name is an atom rather than a variable.
    owner : str
        What the expression belongs to, for diagnostics.

    Returns
    -------
    Term
        The term.

    Raises
    ------
    LexicalError
        If the expression is not a category: a product, a coproduct, a
        space, or a schema spine.
    """
    if isinstance(expr, TypeName):
        if expr.name.isdigit():
            return Node(head=expr.name, form="integer")
        if is_atom(expr.name):
            return atom(expr.name)
        return Variable(name=expr.name)
    if isinstance(expr, ObjectEffectApply):
        return Node(
            head=expr.effect,
            args=tuple(from_object(a, is_atom, owner=owner) for a in expr.args),
            form="apply",
        )
    if isinstance(expr, ObjectSlash):
        return Node(
            head=expr.direction,
            args=(
                from_object(expr.result, is_atom, owner=owner),
                from_object(expr.argument, is_atom, owner=owner),
            ),
            form="slash",
        )
    if isinstance(expr, ObjectFeatures):
        return Node(
            head=expr.atom,
            args=tuple(from_object(a, is_atom, owner=owner) for a in expr.features),
            form="features",
        )
    raise LexicalError(
        f"{owner}: a {type(expr).__name__} is not a category",
        _line(expr),
        _col(expr),
    )

to_object

to_object(term: Term, line: int = 0, col: int = 0) -> ObjectExpr

Write a term as an object expression.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

line

The line the expression carries.

TYPE: int DEFAULT: 0

col

The column the expression carries.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
ObjectExpr

The expression.

RAISES DESCRIPTION
LexicalError

If the term is a string, which no category spells.

Source code in src/quivers/dsl/lexical/terms.py
def to_object(term: Term, line: int = 0, col: int = 0) -> ObjectExpr:
    """Write a term as an object expression.

    Parameters
    ----------
    term : Term
        The term.
    line : int
        The line the expression carries.
    col : int
        The column the expression carries.

    Returns
    -------
    ObjectExpr
        The expression.

    Raises
    ------
    LexicalError
        If the term is a string, which no category spells.
    """
    if isinstance(term, Variable):
        return TypeName(name=term.name, line=line, col=col)
    assert isinstance(term, Node)
    if term.form in ("atom", "integer"):
        return TypeName(name=term.head, line=line, col=col)
    if term.form == "slash":
        result, argument = term.args
        assert term.head in ("/", "\\")
        return ObjectSlash(
            result=to_object(result, line, col),
            argument=to_object(argument, line, col),
            direction="/" if term.head == "/" else "\\",
            line=line,
            col=col,
        )
    if term.form == "features":
        return ObjectFeatures(
            atom=term.head,
            features=tuple(to_object(a, line, col) for a in term.args),
            line=line,
            col=col,
        )
    if term.form == "string":
        raise LexicalError(f"the string {term.head!r} is not a category", line, col)
    return ObjectEffectApply(
        effect=term.head,
        args=tuple(to_object(a, line, col) for a in term.args),
        line=line,
        col=col,
    )

from_meaning

from_meaning(node: LetExprNode, *, owner: str, variables: frozenset[str] = frozenset()) -> Term

Read a lexical meaning as a term.

A name is a variable when it is one of variables (a template's parameter, a category variable); every other name is a constant: an atom, or a name a binder binds.

PARAMETER DESCRIPTION
node

The meaning.

TYPE: LetExprNode

owner

What the meaning belongs to, for diagnostics.

TYPE: str

variables

The names that are variables.

TYPE: frozenset[str] DEFAULT: frozenset()

RETURNS DESCRIPTION
Term

The term.

RAISES DESCRIPTION
LexicalError

If the meaning holds something other than constructor applications, names, integers, and strings.

Source code in src/quivers/dsl/lexical/terms.py
def from_meaning(
    node: LetExprNode,
    *,
    owner: str,
    variables: frozenset[str] = frozenset(),
) -> Term:
    """Read a lexical meaning as a term.

    A name is a variable when it is one of ``variables`` (a template's
    parameter, a category variable); every other name is a constant: an
    atom, or a name a binder binds.

    Parameters
    ----------
    node : LetExprNode
        The meaning.
    owner : str
        What the meaning belongs to, for diagnostics.
    variables : frozenset[str]
        The names that are variables.

    Returns
    -------
    Term
        The term.

    Raises
    ------
    LexicalError
        If the meaning holds something other than constructor
        applications, names, integers, and strings.
    """
    if isinstance(node, LetExprVar):
        if node.name in variables:
            return Variable(name=node.name)
        return atom(node.name)
    if isinstance(node, LetExprCall):
        if node.arg_names and any(node.arg_names):
            raise LexicalError(
                f"{owner}: a meaning applies {node.func!r} to positional arguments",
                node.line,
                node.col,
            )
        return Node(
            head=node.func,
            args=tuple(
                from_meaning(a, owner=owner, variables=variables) for a in node.args
            ),
            form="apply",
        )
    if isinstance(node, LetExprLiteral) and node.integral:
        return Node(head=str(int(node.value)), form="integer")
    if isinstance(node, LetExprString):
        return Node(head=node.value, form="string")
    raise LexicalError(
        f"{owner}: a meaning is a term of constructors, names, and integers, "
        f"not a {type(node).__name__}",
        _line(node),
        _col(node),
    )

to_meaning

to_meaning(term: Term, line: int = 0, col: int = 0) -> LetExprNode

Write a term as a lexical meaning.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

line

The line the expression carries.

TYPE: int DEFAULT: 0

col

The column the expression carries.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
LetExprNode

The meaning.

Source code in src/quivers/dsl/lexical/terms.py
def to_meaning(term: Term, line: int = 0, col: int = 0) -> LetExprNode:
    """Write a term as a lexical meaning.

    Parameters
    ----------
    term : Term
        The term.
    line : int
        The line the expression carries.
    col : int
        The column the expression carries.

    Returns
    -------
    LetExprNode
        The meaning.
    """
    if isinstance(term, Variable):
        return LetExprVar(name=term.name, line=line, col=col)
    assert isinstance(term, Node)
    if term.form == "integer":
        return LetExprLiteral(value=int(term.head), integral=True, line=line, col=col)
    if term.form == "string":
        return LetExprString(value=term.head, line=line, col=col)
    if not term.args and term.form != "apply":
        return LetExprVar(name=term.head, line=line, col=col)
    return LetExprCall(
        func=term.head,
        args=tuple(to_meaning(a, line, col) for a in term.args),
        line=line,
        col=col,
    )

substitute

substitute(term: Term, mapping: Mapping[str, Term]) -> Term

Replace variables by terms.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

mapping

The replacement of each variable; others stay.

TYPE: Mapping[str, Term]

RETURNS DESCRIPTION
Term

The term after replacement.

Source code in src/quivers/dsl/lexical/terms.py
def substitute(term: Term, mapping: Mapping[str, Term]) -> Term:
    """Replace variables by terms.

    Parameters
    ----------
    term : Term
        The term.
    mapping : Mapping[str, Term]
        The replacement of each variable; others stay.

    Returns
    -------
    Term
        The term after replacement.
    """
    if isinstance(term, Variable):
        return mapping.get(term.name, term)
    assert isinstance(term, Node)
    if not term.args:
        return term
    return term.with_(args=tuple(substitute(a, mapping) for a in term.args))

variables_of

variables_of(term: Term) -> tuple[str, ...]

The variables of a term, in order of first occurrence.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
tuple[str, ...]

The variables.

Source code in src/quivers/dsl/lexical/terms.py
def variables_of(term: Term) -> tuple[str, ...]:
    """The variables of a term, in order of first occurrence.

    Parameters
    ----------
    term : Term
        The term.

    Returns
    -------
    tuple[str, ...]
        The variables.
    """
    found: dict[str, None] = {}

    def visit(t: Term) -> None:
        if isinstance(t, Variable):
            found.setdefault(t.name, None)
            return
        assert isinstance(t, Node)
        for a in t.args:
            visit(a)

    visit(term)
    return tuple(found)

depth

depth(term: Term) -> int

The constructor depth of a term: an atom or a variable is 0.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
int

The depth.

Source code in src/quivers/dsl/lexical/terms.py
def depth(term: Term) -> int:
    """The constructor depth of a term: an atom or a variable is 0.

    Parameters
    ----------
    term : Term
        The term.

    Returns
    -------
    int
        The depth.
    """
    if isinstance(term, Variable):
        return 0
    assert isinstance(term, Node)
    if not term.args:
        return 0
    return 1 + max(depth(a) for a in term.args)

match

match(pattern: Term, term: Term, bindings: Mapping[str, Term] | None = None) -> dict[str, Term] | None

Match a pattern against a term, binding the pattern's variables.

The term's own variables are constants to the match.

PARAMETER DESCRIPTION
pattern

The pattern.

TYPE: Term

term

The term.

TYPE: Term

bindings

Bindings that must hold.

TYPE: Mapping[str, Term] | None DEFAULT: None

RETURNS DESCRIPTION
dict[str, Term] | None

The bindings, or None when the term is no instance.

Source code in src/quivers/dsl/lexical/terms.py
def match(
    pattern: Term, term: Term, bindings: Mapping[str, Term] | None = None
) -> dict[str, Term] | None:
    """Match a pattern against a term, binding the pattern's variables.

    The term's own variables are constants to the match.

    Parameters
    ----------
    pattern : Term
        The pattern.
    term : Term
        The term.
    bindings : Mapping[str, Term] | None
        Bindings that must hold.

    Returns
    -------
    dict[str, Term] | None
        The bindings, or None when the term is no instance.
    """
    result = dict(bindings or {})

    def visit(p: Term, t: Term) -> bool:
        if isinstance(p, Variable):
            bound = result.get(p.name)
            if bound is None:
                result[p.name] = t
                return True
            return bound == t
        assert isinstance(p, Node)
        if not isinstance(t, Node):
            return False
        if p.head != t.head or p.form != t.form or len(p.args) != len(t.args):
            return False
        return all(visit(a, b) for a, b in zip(p.args, t.args, strict=True))

    return result if visit(pattern, term) else None

unify

unify(left: Term, right: Term) -> dict[str, Term] | None

A most general unifier of two terms, with the occurs check.

PARAMETER DESCRIPTION
left

One term.

TYPE: Term

right

The other; its variables are distinct from the first's when the caller renamed them apart.

TYPE: Term

RETURNS DESCRIPTION
dict[str, Term] | None

The unifier, fully applied, or None when the terms do not unify.

Source code in src/quivers/dsl/lexical/terms.py
def unify(left: Term, right: Term) -> dict[str, Term] | None:
    """A most general unifier of two terms, with the occurs check.

    Parameters
    ----------
    left : Term
        One term.
    right : Term
        The other; its variables are distinct from the first's when the
        caller renamed them apart.

    Returns
    -------
    dict[str, Term] | None
        The unifier, fully applied, or None when the terms do not unify.
    """
    solution: dict[str, Term] = {}

    def walk(t: Term) -> Term:
        while isinstance(t, Variable) and t.name in solution:
            t = solution[t.name]
        return t

    def occurs(name: str, t: Term) -> bool:
        t = walk(t)
        if isinstance(t, Variable):
            return t.name == name
        assert isinstance(t, Node)
        return any(occurs(name, a) for a in t.args)

    def visit(a: Term, b: Term) -> bool:
        a, b = walk(a), walk(b)
        if isinstance(a, Variable) and isinstance(b, Variable) and a.name == b.name:
            return True
        if isinstance(a, Variable):
            if occurs(a.name, b):
                return False
            solution[a.name] = b
            return True
        if isinstance(b, Variable):
            return visit(b, a)
        assert isinstance(a, Node) and isinstance(b, Node)
        if a.head != b.head or a.form != b.form or len(a.args) != len(b.args):
            return False
        return all(visit(x, y) for x, y in zip(a.args, b.args, strict=True))

    if not visit(left, right):
        return None

    def resolve(t: Term) -> Term:
        t = walk(t)
        if isinstance(t, Variable):
            return t
        assert isinstance(t, Node)
        if not t.args:
            return t
        return t.with_(args=tuple(resolve(a) for a in t.args))

    return {name: resolve(value) for name, value in solution.items()}

rename

rename(term: Term, suffix: str) -> Term

Rename every variable apart by a suffix.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

suffix

Appended to each variable's name.

TYPE: str

RETURNS DESCRIPTION
Term

The renamed term.

Source code in src/quivers/dsl/lexical/terms.py
def rename(term: Term, suffix: str) -> Term:
    """Rename every variable apart by a suffix.

    Parameters
    ----------
    term : Term
        The term.
    suffix : str
        Appended to each variable's name.

    Returns
    -------
    Term
        The renamed term.
    """
    return substitute(
        term, {name: Variable(name=name + suffix) for name in variables_of(term)}
    )

render

render(term: Term) -> str

Spell a term as source writes it.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
str

The spelling.

Source code in src/quivers/dsl/lexical/terms.py
def render(term: Term) -> str:
    """Spell a term as source writes it.

    Parameters
    ----------
    term : Term
        The term.

    Returns
    -------
    str
        The spelling.
    """
    if isinstance(term, Variable):
        return term.name
    assert isinstance(term, Node)
    if term.form == "string":
        return f'"{term.head}"'
    if not term.args:
        return term.head
    if term.form == "slash":
        left, right = term.args
        return f"({render(left)} {term.head} {render(right)})"
    if term.form == "features":
        return f"{term.head}[{', '.join(render(a) for a in term.args)}]"
    return f"{term.head}({', '.join(render(a) for a in term.args)})"