Skip to content

Notation

Scoped notation, mixfix enforestation, hygienic expansion by sets of scopes, quotation elaboration, and printing. The notation reference describes the surface, and the semantics states the rules.

notation

Scoped notation, mixfix operators, and typed quotation.

A notation declaration gives mixfix productions over the terms of a binding signature; open notation activates notations for the rest of a module; a quotation [| ... |] is read against the active notations' precedence DAG, expanded hygienically by sets of scopes into the de Bruijn term it means, and elaborated to the constructor tree (or pattern) of that term. Terms print back through the active notations, on the host and in the generated Show instances; a quotation annotated with a quoted-syntax family of the meta phase quotes QVR itself.

CODE_FAMILIES module-attribute

CODE_FAMILIES = frozenset({'SynDecl', 'SynComp', 'SynValue', 'SynType', 'SynPattern'})

The quoted-syntax families a code quotation may be annotated with.

SHOW_MEMBER module-attribute

SHOW_MEMBER = 'show'

The member name of a family's Show instance.

NOTATION_KIND module-attribute

NOTATION_KIND = 'notation'

The declaration kind of a notation.

CONTEXT_TURNSTILE module-attribute

CONTEXT_TURNSTILE = '⊢'

The token that ends a quotation's context, as in [| x, y ⊢ x y |].

NOTATION_CODE module-attribute

NOTATION_CODE = 'qiec-notation'

The diagnostic code of every notation and quotation refusal.

ReferenceResolver module-attribute

ReferenceResolver = Callable[[str, int, int], tuple[str, ...]]

Resolves an open notation target (as written, with its line and column) to the flat names of the notations it activates.

SortKey

SortKey = tuple[str, str] | None

A signature and one of its sorts, or None when not yet known.

SyntaxValue

SyntaxValue = Model | tuple[SyntaxValue, ...] | str | int | float | bool | None

A syntax node, a tuple of them, or a leaf of one.

Associativity

Associativity = Literal['left', 'right', 'none']

How an infix production chains with itself and its level.

Fixity

Fixity = Literal['closed', 'prefix', 'postfix', 'infix']

Where a production's outer operand holes are: none, last, first, or both.

Located

Every token kind; each has a span and a location.

NotationProgram

NotationProgram(notations: Mapping[str, NotationDecl], syntaxes: Mapping[str, SyntaxInfo], files: Mapping[str, str])

The notations and signatures of a program, and the tables they form.

PARAMETER DESCRIPTION
notations

Every notation declaration, by flat name.

TYPE: Mapping[str, NotationDecl]

syntaxes

Every binding signature, by flat name.

TYPE: Mapping[str, SyntaxInfo]

files

The file each notation is declared in.

TYPE: Mapping[str, str]

Source code in src/quivers/dsl/notation/elaborate.py
def __init__(
    self,
    notations: Mapping[str, NotationDecl],
    syntaxes: Mapping[str, SyntaxInfo],
    files: Mapping[str, str],
) -> None:
    self.notations = dict(notations)
    self.syntaxes = dict(syntaxes)
    self.files = dict(files)
    self._tables: dict[tuple[str, ...], NotationTable] = {}

table

table(active: tuple[str, ...], *, file: str, line: int, col: int) -> NotationTable

The table of a set of active notations.

PARAMETER DESCRIPTION
active

The flat names of the active notations, in activation order.

TYPE: tuple[str, ...]

file

The file of the point that needs it.

TYPE: str

line

That point's location.

TYPE: int

col

That point's location.

TYPE: int

RETURNS DESCRIPTION
NotationTable

The table, built once per set.

RAISES DESCRIPTION
QiecDiagnosticError

If no notation is active, or the active notations do not form a table.

Source code in src/quivers/dsl/notation/elaborate.py
def table(
    self, active: tuple[str, ...], *, file: str, line: int, col: int
) -> NotationTable:
    """The table of a set of active notations.

    Parameters
    ----------
    active : tuple[str, ...]
        The flat names of the active notations, in activation order.
    file : str
        The file of the point that needs it.
    line, col : int
        That point's location.

    Returns
    -------
    NotationTable
        The table, built once per set.

    Raises
    ------
    QiecDiagnosticError
        If no notation is active, or the active notations do not form a
        table.
    """
    if not active:
        raise fail(
            "no notation is active here; activate one with `open notation N`",
            file=file,
            line=line,
            col=col,
        )
    found = self._tables.get(active)
    if found is None:
        found = build_table(
            active,
            self.notations,
            self.syntaxes,
            self.files,
            file=file,
            line=line,
            col=col,
        )
        self._tables[active] = found
    return found

sort_of_type

sort_of_type(type_expr: QiecTypeExpr) -> SortKey

The signature sort a type names, if it names one.

PARAMETER DESCRIPTION
type_expr

A type.

TYPE: QiecTypeExpr

RETURNS DESCRIPTION
SortKey

(signature, sort) when the type is a signature family.

Source code in src/quivers/dsl/notation/elaborate.py
def sort_of_type(self, type_expr: QiecTypeExpr) -> SortKey:
    """The signature sort a type names, if it names one.

    Parameters
    ----------
    type_expr : QiecTypeExpr
        A type.

    Returns
    -------
    SortKey
        ``(signature, sort)`` when the type is a signature family.
    """
    if isinstance(type_expr, QiecTypeName):
        name = type_expr.name
    elif isinstance(type_expr, QiecTypeApplication) and not type_expr.arguments:
        name = type_expr.constructor
    else:
        return None
    for info in self.syntaxes.values():
        for sort in info.signature.sorts_t:
            if family_name(info.name, sort.name) == name:
                return (info.name, sort.name)
    return None

Quoted didactic-model

Quoted(*, core: CoreNode, syntax: str = '', sort: str = '', context: tuple[str, ...] = (), reading: Reading | None = None)

Bases: Model

A quotation read and expanded.

PARAMETER DESCRIPTION
core

Its meaning.

TYPE: CoreNode

syntax

The flat name of its signature, empty for a bare antiquotation.

TYPE: str DEFAULT: ''

sort

Its sort, empty for a bare antiquotation.

TYPE: str DEFAULT: ''

context

The names of its free variables, outermost first.

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

reading

How it was read, for tooling.

TYPE: Reading | None DEFAULT: None

term

term() -> Term

The host term of a quotation that splices nothing.

RETURNS DESCRIPTION
Term

The de Bruijn term.

Source code in src/quivers/dsl/notation/elaborate.py
def term(self) -> Term:
    """The host term of a quotation that splices nothing.

    Returns
    -------
    Term
        The de Bruijn term.
    """
    return core_term(self.core)

ArgumentAbstraction didactic-model

ArgumentAbstraction(*, names: tuple[TokenName, ...], body: ParseNode, kind: Literal['argument_abstraction'] = 'argument_abstraction')

Bases: ParseArgument

x y. body: an argument that binds variables.

PARAMETER DESCRIPTION
names

The bound names.

TYPE: tuple[TokenName, ...]

body

The body.

TYPE: ParseNode

ArgumentLiteral didactic-model

ArgumentLiteral(*, literal: TokenLiteral, kind: Literal['argument_literal'] = 'argument_literal')

Bases: ParseArgument

A data argument.

PARAMETER DESCRIPTION
literal

The literal.

TYPE: TokenLiteral

ArgumentTerm didactic-model

ArgumentTerm(*, node: ParseNode, kind: Literal['argument_term'] = 'argument_term')

Bases: ParseArgument

An argument that binds nothing.

PARAMETER DESCRIPTION
node

The argument.

TYPE: ParseNode

FillBinder didactic-model

FillBinder(*, name: TokenName, kind: Literal['fill_binder'] = 'fill_binder')

Bases: ParseFill

A binder hole's name.

PARAMETER DESCRIPTION
name

The name the quotation binds there.

TYPE: TokenName

FillData didactic-model

FillData(*, literal: TokenLiteral, kind: Literal['fill_data'] = 'fill_data')

Bases: ParseFill

A data hole's literal.

PARAMETER DESCRIPTION
literal

The literal.

TYPE: TokenLiteral

FillOperand didactic-model

FillOperand(*, node: ParseNode, kind: Literal['fill_operand'] = 'fill_operand')

Bases: ParseFill

An operand hole's reading.

PARAMETER DESCRIPTION
node

The operand.

TYPE: ParseNode

FillToken didactic-model

FillToken(*, token: TokenWord, kind: Literal['fill_token'] = 'fill_token')

Bases: ParseFill

A token a production's shape matched, kept for tooling.

PARAMETER DESCRIPTION
token

The token.

TYPE: TokenWord

ParseAntiquote didactic-model

ParseAntiquote(*, token: TokenAntiquote, kind: Literal['parse_antiquote'] = 'parse_antiquote')

Bases: ParseNode

An antiquotation.

PARAMETER DESCRIPTION
token

The antiquotation.

TYPE: TokenAntiquote

ParseArgument didactic-model

ParseArgument()

Bases: TaggedUnion

One argument of a constructor application.

ParseConstructor didactic-model

ParseConstructor(*, op: str, args: tuple[ParseArgument, ...] = (), token: TokenName, kind: Literal['parse_constructor'] = 'parse_constructor')

Bases: ParseNode

A constructor application Op(...) written in a quotation.

PARAMETER DESCRIPTION
op

The constructor's flat name.

TYPE: str

args

Its arguments.

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

token

The constructor's name as written.

TYPE: TokenName

ParseFill didactic-model

ParseFill()

Bases: TaggedUnion

What fills one hole of a production.

ParseName didactic-model

ParseName(*, token: TokenName, kind: Literal['parse_name'] = 'parse_name')

Bases: ParseNode

A name: a variable or a nullary constructor.

PARAMETER DESCRIPTION
token

The name.

TYPE: TokenName

ParseNode didactic-model

ParseNode()

Bases: TaggedUnion

A reading of (part of) a quotation.

ParseUse didactic-model

ParseUse(*, production: str, fills: tuple[ParseFill, ...] = (), line: int = 0, col: int = 0, kind: Literal['parse_use'] = 'parse_use')

Bases: ParseNode

A production applied to its holes' fills.

PARAMETER DESCRIPTION
production

The production's qualified name.

TYPE: str

fills

One fill per hole and one FillToken per token, in shape order.

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

line

Where the use starts.

TYPE: int DEFAULT: 0

col

Where the use starts.

TYPE: int DEFAULT: 0

Reading didactic-model

Reading(*, node: ParseNode, sort: str = '', syntax: str = '')

Bases: Model

A complete reading of a quotation.

PARAMETER DESCRIPTION
node

The reading.

TYPE: ParseNode

sort

The sort it builds, or empty when only its context decides (a name or an antiquotation).

TYPE: str DEFAULT: ''

syntax

The signature of that sort, or empty.

TYPE: str DEFAULT: ''

CoreAntiquote didactic-model

CoreAntiquote(*, antiquote: NotationAntiquote, syntax: str, sort: str, shifts: tuple[CoreShift, ...] = (), depth: int = 0, kind: Literal['core_antiquote'] = 'core_antiquote')

Bases: CoreNode

A spliced host value, weakened past the binders its author cannot see.

PARAMETER DESCRIPTION
antiquote

The antiquotation.

TYPE: NotationAntiquote

syntax

The signature of the expected sort.

TYPE: str

sort

The expected sort.

TYPE: str

shifts

The weakenings, innermost binder first.

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

depth

How many binders of the quotation enclose it.

TYPE: int DEFAULT: 0

CoreApply didactic-model

CoreApply(*, op: str, syntax: str, args: tuple[CoreNode, ...] = (), kind: Literal['core_apply'] = 'core_apply')

Bases: CoreNode

A constructor applied to its arguments.

PARAMETER DESCRIPTION
op

The constructor's flat name.

TYPE: str

syntax

Its signature's flat name.

TYPE: str

args

Its arguments; a binding argument is a CoreBinding.

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

CoreBinding didactic-model

CoreBinding(*, names: tuple[str, ...], body: CoreNode, kind: Literal['core_binding'] = 'core_binding')

Bases: CoreNode

A binding argument: its body in the scope of its variables.

PARAMETER DESCRIPTION
names

The names the quotation gave the bound variables, for display.

TYPE: tuple[str, ...]

body

The body.

TYPE: CoreNode

CoreLeaf didactic-model

CoreLeaf(*, text: str = '', number: int = 0, is_text: bool = True, kind: Literal['core_leaf'] = 'core_leaf')

Bases: CoreNode

A data literal.

PARAMETER DESCRIPTION
text

Its value, for a string.

TYPE: str DEFAULT: ''

number

Its value, for an integer.

TYPE: int DEFAULT: 0

is_text

Whether it is a string.

TYPE: bool DEFAULT: True

CoreNode didactic-model

CoreNode()

Bases: TaggedUnion

A quotation's meaning: a de Bruijn term that may splice host values.

CoreShift didactic-model

CoreShift(*, cutoff: int, amount: int = 1)

Bases: Model

Weakening a spliced term past one binder its author cannot see.

PARAMETER DESCRIPTION
cutoff

Variables below the cutoff keep their index.

TYPE: int

amount

What the others gain.

TYPE: int DEFAULT: 1

CoreVariable didactic-model

CoreVariable(*, index: int, syntax: str, sort: str, kind: Literal['core_variable'] = 'core_variable')

Bases: CoreNode

A variable by de Bruijn index.

PARAMETER DESCRIPTION
index

The index.

TYPE: int

syntax

The signature's flat name.

TYPE: str

sort

The variable's sort.

TYPE: str

Syntax didactic-model

Syntax()

Bases: TaggedUnion

Expanded syntax whose names carry sets of scopes.

SyntaxAbstraction didactic-model

SyntaxAbstraction(*, names: tuple[SyntaxName, ...], body: Syntax, kind: Literal['syntax_abstraction'] = 'syntax_abstraction')

Bases: Syntax

Names bound over a body: a binding argument.

PARAMETER DESCRIPTION
names

The binders, outermost first.

TYPE: tuple[SyntaxName, ...]

body

The body.

TYPE: Syntax

SyntaxAntiquote didactic-model

SyntaxAntiquote(*, antiquote: NotationAntiquote, scopes: tuple[int, ...], kind: Literal['syntax_antiquote'] = 'syntax_antiquote')

Bases: Syntax

An antiquotation and the scopes of where its author wrote it.

PARAMETER DESCRIPTION
antiquote

The antiquotation.

TYPE: NotationAntiquote

scopes

Its scopes.

TYPE: tuple[int, ...]

SyntaxApply didactic-model

SyntaxApply(*, op: str, args: tuple[Syntax, ...] = (), line: int = 0, col: int = 0, kind: Literal['syntax_apply'] = 'syntax_apply')

Bases: Syntax

A constructor applied to arguments.

PARAMETER DESCRIPTION
op

The constructor's flat name.

TYPE: str

args

Its arguments.

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

line

Where it is written.

TYPE: int DEFAULT: 0

col

Where it is written.

TYPE: int DEFAULT: 0

SyntaxLeaf didactic-model

SyntaxLeaf(*, text: str = '', number: int = 0, is_text: bool = True, line: int = 0, col: int = 0, kind: Literal['syntax_leaf'] = 'syntax_leaf')

Bases: Syntax

A data literal.

PARAMETER DESCRIPTION
text

Its value, for a string.

TYPE: str DEFAULT: ''

number

Its value, for an integer.

TYPE: int DEFAULT: 0

is_text

Whether it is a string.

TYPE: bool DEFAULT: True

line

Where it is written.

TYPE: int DEFAULT: 0

col

Where it is written.

TYPE: int DEFAULT: 0

SyntaxName didactic-model

SyntaxName(*, text: str, scopes: tuple[int, ...], line: int = 0, col: int = 0, kind: Literal['syntax_name'] = 'syntax_name')

Bases: Syntax

A name and its scopes.

PARAMETER DESCRIPTION
text

The name.

TYPE: str

scopes

Its scopes, sorted.

TYPE: tuple[int, ...]

line

Where it is written (for a template name, where the production is used).

TYPE: int DEFAULT: 0

col

Where it is written (for a template name, where the production is used).

TYPE: int DEFAULT: 0

ModuleNotations

ModuleNotations(checked: CheckedModule, interfaces: dict[ModuleIdentity, ModuleInterface], root: ModuleIdentity)

Resolve notation references in one module of a graph.

PARAMETER DESCRIPTION
checked

The module, resolved against its dependencies.

TYPE: CheckedModule

interfaces

Every module's interface.

TYPE: dict[ModuleIdentity, ModuleInterface]

root

The program's root module.

TYPE: ModuleIdentity

Source code in src/quivers/dsl/notation/scoping.py
def __init__(
    self,
    checked: CheckedModule,
    interfaces: dict[ModuleIdentity, ModuleInterface],
    root: ModuleIdentity,
) -> None:
    self.checked = checked
    self.interfaces = interfaces
    self.root = root
    self.file = checked.source.label

flat

flat(module: ModuleIdentity, name: str) -> str

The flat-program name of a module's declaration.

PARAMETER DESCRIPTION
module

The declaring module.

TYPE: ModuleIdentity

name

The name in it.

TYPE: str

RETURNS DESCRIPTION
str

The bare name in the root module, module:name elsewhere.

Source code in src/quivers/dsl/notation/scoping.py
def flat(self, module: ModuleIdentity, name: str) -> str:
    """The flat-program name of a module's declaration.

    Parameters
    ----------
    module : ModuleIdentity
        The declaring module.
    name : str
        The name in it.

    Returns
    -------
    str
        The bare name in the root module, ``module:name`` elsewhere.
    """
    if module == self.root:
        return name
    return flat_name(module, name)

exported

exported(module: ModuleIdentity) -> tuple[str, ...]

The flat names of the notations a module exports.

PARAMETER DESCRIPTION
module

The module.

TYPE: ModuleIdentity

RETURNS DESCRIPTION
tuple[str, ...]

In declaration order.

Source code in src/quivers/dsl/notation/scoping.py
def exported(self, module: ModuleIdentity) -> tuple[str, ...]:
    """The flat names of the notations a module exports.

    Parameters
    ----------
    module : ModuleIdentity
        The module.

    Returns
    -------
    tuple[str, ...]
        In declaration order.
    """
    return tuple(
        self.flat(entry.origin, entry.origin_name)
        for entry in self.interfaces[module].entries
        if NOTATION_KIND in entry.kinds
    )

resolve

resolve(target: str, line: int, col: int) -> tuple[str, ...]

The notations a reference names.

PARAMETER DESCRIPTION
target

A notation (bare, or qualified by an import) or a module.

TYPE: str

line

Where it is written.

TYPE: int

col

Where it is written.

TYPE: int

RETURNS DESCRIPTION
tuple[str, ...]

The flat names of the notations.

RAISES DESCRIPTION
QiecDiagnosticError

If the reference names no notation and no imported module.

Source code in src/quivers/dsl/notation/scoping.py
def resolve(self, target: str, line: int, col: int) -> tuple[str, ...]:
    """The notations a reference names.

    Parameters
    ----------
    target : str
        A notation (bare, or qualified by an import) or a module.
    line, col : int
        Where it is written.

    Returns
    -------
    tuple[str, ...]
        The flat names of the notations.

    Raises
    ------
    QiecDiagnosticError
        If the reference names no notation and no imported module.
    """
    own = {
        item.name
        for item in self.checked.names.declarations
        if item.kind == NOTATION_KIND
    }
    if target in own:
        return (self.flat(self.checked.identity, target),)
    for resolved in self.checked.imports:
        record = resolved.record
        names = {record.path} | ({record.alias} if record.alias else set())
        if target in names:
            found = self.exported(resolved.module)
            if not found:
                raise fail(
                    f"module {record.path} exports no notation",
                    file=self.file,
                    line=line,
                    col=col,
                )
            return found
        for prefix in names:
            if target.startswith(f"{prefix}."):
                entry = self.interfaces[resolved.module].get(
                    target[len(prefix) + 1 :]
                )
                if entry is not None and NOTATION_KIND in entry.kinds:
                    return (self.flat(entry.origin, entry.origin_name),)
        selected = {item.name for item in record.items or ()}
        if target in selected:
            entry = self.interfaces[resolved.module].get(target)
            if entry is not None and NOTATION_KIND in entry.kinds:
                return (self.flat(entry.origin, entry.origin_name),)
    for opened in self.checked.names.opens:
        for resolved in self.checked.imports:
            record = resolved.record
            if opened.module not in (record.path, record.alias):
                continue
            entry = self.interfaces[resolved.module].get(target)
            if entry is not None and NOTATION_KIND in entry.kinds:
                return (self.flat(entry.origin, entry.origin_name),)
    raise fail(
        f"`{target}` names no notation and no imported module",
        file=self.file,
        line=line,
        col=col,
    )

relation

relation(notation: NotationDecl, relation: NotationRelation) -> NotationRelation

A relation with its other notations' productions named by flat name.

PARAMETER DESCRIPTION
notation

The declaring notation.

TYPE: NotationDecl

relation

One of its relations.

TYPE: NotationRelation

RETURNS DESCRIPTION
NotationRelation

The relation; a bare production name stays bare (a production of the declaring notation).

RAISES DESCRIPTION
QiecDiagnosticError

If a qualified production's notation does not resolve to one notation.

Source code in src/quivers/dsl/notation/scoping.py
def relation(
    self, notation: NotationDecl, relation: NotationRelation
) -> NotationRelation:
    """A relation with its other notations' productions named by flat name.

    Parameters
    ----------
    notation : NotationDecl
        The declaring notation.
    relation : NotationRelation
        One of its relations.

    Returns
    -------
    NotationRelation
        The relation; a bare production name stays bare (a production
        of the declaring notation).

    Raises
    ------
    QiecDiagnosticError
        If a qualified production's notation does not resolve to one
        notation.
    """
    own = {production.name for production in notation.productions}

    def qualify(reference: str) -> str:
        if reference in own or "." not in reference:
            return reference
        target, _, production = reference.rpartition(".")
        found = self.resolve(target, relation.line, relation.col)
        if len(found) != 1:
            raise fail(
                f"`{target}` names a module; qualify `{production}` by its notation",
                file=self.file,
                line=relation.line,
                col=relation.col,
            )
        return member_name(found[0], production)

    return relation.with_(
        left=qualify(relation.left), right=qualify(relation.right)
    )

Level didactic-model

Level(*, members: tuple[str, ...], tighter: tuple[int, ...] = ())

Bases: Model

One precedence level: productions that relate as one.

PARAMETER DESCRIPTION
members

The qualified names of its productions.

TYPE: tuple[str, ...]

tighter

The levels that bind strictly tighter, transitively.

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

NotationTable didactic-model

NotationTable(*, notations: tuple[str, ...] = (), productions: tuple[Production, ...] = (), levels: tuple[Level, ...] = (), level_of: tuple[int, ...] = (), syntaxes: tuple[SyntaxInfo, ...] = ())

Bases: Model

The active notations of one point of a module.

PARAMETER DESCRIPTION
notations

The flat names of the active notations, in activation order.

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

productions

Their productions.

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

levels

The precedence levels.

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

level_of

Each production's level, by position in productions.

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

syntaxes

The signatures the notations are for.

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

tighter_sets cached property

tighter_sets: tuple[frozenset[int], ...]

Each level's strictly tighter levels.

RETURNS DESCRIPTION
tuple[frozenset[int], ...]

By level.

tokens cached property

tokens: frozenset[str]

Every token of the active productions.

RETURNS DESCRIPTION
frozenset[str]

The tokens.

symbol_tokens cached property

symbol_tokens: tuple[str, ...]

The symbol tokens, longest first, for maximal munch.

RETURNS DESCRIPTION
tuple[str, ...]

The tokens that are not names.

reading_symbols cached property

reading_symbols: tuple[str, ...]

The symbol tokens a quotation's symbol runs split into.

RETURNS DESCRIPTION
tuple[str, ...]

The active symbol tokens and the punctuation of constructor application, , and ., longest first.

word_tokens cached property

word_tokens: frozenset[str]

The tokens spelled like names, which quotations read as tokens.

RETURNS DESCRIPTION
frozenset[str]

The name-like tokens.

constructors cached property

constructors: dict[str, tuple[SyntaxInfo, str]]

Every constructor of the active signatures with its signature.

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

By flat constructor name: the signature and the constructor's codomain.

level

level(production: Production) -> int

The precedence level of a production.

PARAMETER DESCRIPTION
production

An active production.

TYPE: Production

RETURNS DESCRIPTION
int

Its level.

Source code in src/quivers/dsl/notation/table.py
def level(self, production: Production) -> int:
    """The precedence level of a production.

    Parameters
    ----------
    production : Production
        An active production.

    Returns
    -------
    int
        Its level.
    """
    return self.level_of[self._index[production.qualified]]

unrelated

unrelated(left: int, right: int) -> bool

Whether two levels are distinct and ordered neither way.

PARAMETER DESCRIPTION
left

Two levels.

TYPE: int

right

Two levels.

TYPE: int

RETURNS DESCRIPTION
bool

True when no relation orders them.

Source code in src/quivers/dsl/notation/table.py
def unrelated(self, left: int, right: int) -> bool:
    """Whether two levels are distinct and ordered neither way.

    Parameters
    ----------
    left, right : int
        Two levels.

    Returns
    -------
    bool
        True when no relation orders them.
    """
    return (
        left != right
        and right not in self.tighter_sets[left]
        and left not in self.tighter_sets[right]
    )

syntax

syntax(name: str) -> SyntaxInfo

One active signature by flat name.

PARAMETER DESCRIPTION
name

The signature.

TYPE: str

RETURNS DESCRIPTION
SyntaxInfo

It.

RAISES DESCRIPTION
KeyError

If no active notation is for it.

Source code in src/quivers/dsl/notation/table.py
def syntax(self, name: str) -> SyntaxInfo:
    """One active signature by flat name.

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

    Returns
    -------
    SyntaxInfo
        It.

    Raises
    ------
    KeyError
        If no active notation is for it.
    """
    for info in self.syntaxes:
        if info.name == name:
            return info
    raise KeyError(name)

productions_for

productions_for(syntax: str, sort: str) -> tuple[Production, ...]

The productions that build a sort of a signature.

PARAMETER DESCRIPTION
syntax

The signature.

TYPE: str

sort

The sort.

TYPE: str

RETURNS DESCRIPTION
tuple[Production, ...]

In activation order.

Source code in src/quivers/dsl/notation/table.py
def productions_for(self, syntax: str, sort: str) -> tuple[Production, ...]:
    """The productions that build a sort of a signature.

    Parameters
    ----------
    syntax : str
        The signature.
    sort : str
        The sort.

    Returns
    -------
    tuple[Production, ...]
        In activation order.
    """
    return tuple(
        p for p in self.productions if p.syntax == syntax and p.sort == sort
    )

Production didactic-model

Production(*, notation: str, name: str, syntax: str, items: tuple[ShapeItem, ...], template: TemplateNode, sort: str, assoc: Associativity = 'none', order: int = 0, line: int = 0, col: int = 0, file: str = '')

Bases: Model

A production read against its signature.

PARAMETER DESCRIPTION
notation

The flat name of the notation that declares it.

TYPE: str

name

Its name in the notation.

TYPE: str

syntax

The flat name of the signature its template is a term of.

TYPE: str

items

Its shape.

TYPE: tuple[ShapeItem, ...]

template

The term it stands for.

TYPE: TemplateNode

sort

The sort the template builds.

TYPE: str

assoc

Its associativity.

TYPE: Associativity DEFAULT: 'none'

order

Its position among the active productions, which breaks ties when printing.

TYPE: int DEFAULT: 0

line

Where it is declared.

TYPE: int DEFAULT: 0

col

Where it is declared.

TYPE: int DEFAULT: 0

file

The file it is declared in.

TYPE: str DEFAULT: ''

qualified property

qualified: str

The production's name qualified by its notation.

RETURNS DESCRIPTION
str

notation.production.

label property

label: str

The production for messages: its name, notation, and module.

RETURNS DESCRIPTION
str

production `app` of notation N of module m.

elements property

elements: tuple[ShapeItem, ...]

The items that take part in reading: every item but printing space.

RETURNS DESCRIPTION
tuple[ShapeItem, ...]

Tokens and holes, in order.

fixity property

fixity: Fixity

Where the production's outer operand holes are.

A binder or data hole reads one token, so it delimits like a token does.

RETURNS DESCRIPTION
Fixity

closed, prefix, postfix, or infix.

binder_holes property

binder_holes: frozenset[str]

The names of the binder holes.

RETURNS DESCRIPTION
frozenset[str]

The holes an abstraction of the template binds.

shape_key property

shape_key: tuple[str, ...]

What two productions that read the same text share.

RETURNS DESCRIPTION
tuple[str, ...]

The tokens and hole roles of the shape, with the result sort.

hole

hole(name: str) -> ShapeItem

One hole of the shape.

PARAMETER DESCRIPTION
name

The hole's name.

TYPE: str

RETURNS DESCRIPTION
ShapeItem

The hole.

RAISES DESCRIPTION
KeyError

If the shape has no hole of that name.

Source code in src/quivers/dsl/notation/table.py
def hole(self, name: str) -> ShapeItem:
    """One hole of the shape.

    Parameters
    ----------
    name : str
        The hole's name.

    Returns
    -------
    ShapeItem
        The hole.

    Raises
    ------
    KeyError
        If the shape has no hole of that name.
    """
    for item in self.items:
        if item.role in ("operand", "binder", "data") and item.text == name:
            return item
    raise KeyError(name)

ShapeItem didactic-model

ShapeItem(*, role: ShapeRole, text: str, before: str = '', after: str = '', sort: str = '', line: int = 0, col: int = 0)

Bases: Model

One item of a production's shape.

PARAMETER DESCRIPTION
role

A token, a run of printing space, an operand hole, a binder hole, or a data hole.

TYPE: ShapeRole

text

The token without its printing space, the space itself, or the hole's name.

TYPE: str

before

Printing space written before a token.

TYPE: str DEFAULT: ''

after

Printing space written after a token.

TYPE: str DEFAULT: ''

sort

A hole's sort: the operand's object sort, the bound variable's sort, or the data sort.

TYPE: str DEFAULT: ''

line

Where the item is written.

TYPE: int DEFAULT: 0

col

Where the item is written.

TYPE: int DEFAULT: 0

SyntaxInfo didactic-model

SyntaxInfo(*, name: str, signature: Signature)

Bases: Model

A binding signature as notation reads it.

PARAMETER DESCRIPTION
name

The signature's flat name.

TYPE: str

signature

The signature.

TYPE: Signature

is_object

is_object(sort: str) -> bool

Whether a sort is an object sort, whose terms notation writes.

PARAMETER DESCRIPTION
sort

The sort.

TYPE: str

RETURNS DESCRIPTION
bool

True for an object sort.

Source code in src/quivers/dsl/notation/table.py
def is_object(self, sort: str) -> bool:
    """Whether a sort is an object sort, whose terms notation writes.

    Parameters
    ----------
    sort : str
        The sort.

    Returns
    -------
    bool
        True for an ``object`` sort.
    """
    found = self.signature.sorts.get(sort)
    return found is not None and found.kind == "object"

TemplateAbstraction didactic-model

TemplateAbstraction(*, names: tuple[str, ...], body: TemplateNode, kind: Literal['template_abstraction'] = 'template_abstraction')

Bases: TemplateNode

x y. body: the argument of a binding position.

PARAMETER DESCRIPTION
names

The bound names: binder holes, or names the template binds itself.

TYPE: tuple[str, ...]

body

The body.

TYPE: TemplateNode

TemplateApply didactic-model

TemplateApply(*, op: str, args: tuple[TemplateNode, ...] = (), kind: Literal['template_apply'] = 'template_apply')

Bases: TemplateNode

A constructor applied to arguments.

PARAMETER DESCRIPTION
op

The constructor's flat name.

TYPE: str

args

Its arguments; an argument that binds is a TemplateAbstraction.

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

TemplateHole didactic-model

TemplateHole(*, name: str, kind: Literal['template_hole'] = 'template_hole')

Bases: TemplateNode

An operand or data hole.

PARAMETER DESCRIPTION
name

The hole.

TYPE: str

TemplateLeaf didactic-model

TemplateLeaf(*, text: str = '', number: int = 0, is_text: bool = True, kind: Literal['template_leaf'] = 'template_leaf')

Bases: TemplateNode

A data literal of the template.

PARAMETER DESCRIPTION
text

The literal's value, for a string.

TYPE: str DEFAULT: ''

number

The literal's value, for an integer.

TYPE: int DEFAULT: 0

is_text

Whether the literal is a string.

TYPE: bool DEFAULT: True

TemplateNode didactic-model

TemplateNode()

Bases: TaggedUnion

A production's template: a term of the signature over its holes.

TemplateVariable didactic-model

TemplateVariable(*, name: str, kind: Literal['template_variable'] = 'template_variable')

Bases: TemplateNode

A reference to a variable a template abstraction binds.

PARAMETER DESCRIPTION
name

The variable's name in the template; when it is a binder hole, the variable is the one the user names there.

TYPE: str

QuotationText didactic-model

QuotationText(*, context: tuple[TokenName, ...] = (), tokens: tuple[ReadToken, ...] = ())

Bases: Model

A quotation's tokens and the context it declares.

PARAMETER DESCRIPTION
context

The names before ⊢, outermost first: the free variables the quoted term may mention.

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

tokens

The quoted term's tokens.

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

ReadToken didactic-model

ReadToken()

Bases: TaggedUnion

One token of a quotation, as the mixfix reader sees it.

TokenAntiquote didactic-model

TokenAntiquote(*, antiquote: NotationAntiquote, start: int = 0, end: int = 0, line: int = 0, col: int = 0, kind: Literal['token_antiquote'] = 'token_antiquote')

Bases: ReadToken

An antiquotation.

PARAMETER DESCRIPTION
antiquote

The antiquotation as written.

TYPE: NotationAntiquote

start

Its byte span.

TYPE: int DEFAULT: 0

end

Its byte span.

TYPE: int DEFAULT: 0

line

Its location.

TYPE: int DEFAULT: 0

col

Its location.

TYPE: int DEFAULT: 0

TokenGroup didactic-model

TokenGroup(*, items: tuple[ReadToken, ...] = (), start: int = 0, end: int = 0, line: int = 0, col: int = 0, kind: Literal['token_group'] = 'token_group')

Bases: ReadToken

A parenthesized group.

PARAMETER DESCRIPTION
items

Its tokens.

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

start

Its byte span.

TYPE: int DEFAULT: 0

end

Its byte span.

TYPE: int DEFAULT: 0

line

Its location.

TYPE: int DEFAULT: 0

col

Its location.

TYPE: int DEFAULT: 0

TokenLiteral didactic-model

TokenLiteral(*, text: str, string: str = '', number: int = 0, is_text: bool = True, start: int = 0, end: int = 0, line: int = 0, col: int = 0, kind: Literal['token_literal'] = 'token_literal')

Bases: ReadToken

A string or integer literal, the value of a data hole.

PARAMETER DESCRIPTION
text

The literal as written.

TYPE: str

string

Its value, for a string.

TYPE: str DEFAULT: ''

number

Its value, for an integer.

TYPE: int DEFAULT: 0

is_text

Whether it is a string.

TYPE: bool DEFAULT: True

start

Its byte span.

TYPE: int DEFAULT: 0

end

Its byte span.

TYPE: int DEFAULT: 0

line

Its location.

TYPE: int DEFAULT: 0

col

Its location.

TYPE: int DEFAULT: 0

TokenName didactic-model

TokenName(*, text: str, start: int = 0, end: int = 0, line: int = 0, col: int = 0, kind: Literal['token_name'] = 'token_name')

Bases: ReadToken

A name: a variable, a constructor, or a binder.

PARAMETER DESCRIPTION
text

The name.

TYPE: str

start

Its byte span.

TYPE: int DEFAULT: 0

end

Its byte span.

TYPE: int DEFAULT: 0

line

Its location.

TYPE: int DEFAULT: 0

col

Its location.

TYPE: int DEFAULT: 0

TokenWord didactic-model

TokenWord(*, text: str, start: int = 0, end: int = 0, line: int = 0, col: int = 0, kind: Literal['token_word'] = 'token_word')

Bases: ReadToken

A token of an active notation.

PARAMETER DESCRIPTION
text

The token.

TYPE: str

start

Its byte span.

TYPE: int DEFAULT: 0

end

Its byte span.

TYPE: int DEFAULT: 0

line

Its location.

TYPE: int DEFAULT: 0

col

Its location.

TYPE: int DEFAULT: 0

code_quotation

code_quotation(quotation: QiecQuotation, family: str, *, file: str) -> LetExprNode

The quoted-syntax constructor tree of a code quotation.

PARAMETER DESCRIPTION
quotation

The quotation.

TYPE: QiecQuotation

family

SynDecl, SynComp, SynValue, SynType, or SynPattern.

TYPE: str

file

The file, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
LetExprNode

The constructor tree, antiquotations in place.

RAISES DESCRIPTION
QiecDiagnosticError

If the contents do not parse as that category, or use a form the quoted-syntax families do not represent.

Source code in src/quivers/dsl/notation/code.py
def code_quotation(quotation: QiecQuotation, family: str, *, file: str) -> LetExprNode:
    """The quoted-syntax constructor tree of a code quotation.

    Parameters
    ----------
    quotation : QiecQuotation
        The quotation.
    family : str
        ``SynDecl``, ``SynComp``, ``SynValue``, ``SynType``, or
        ``SynPattern``.
    file : str
        The file, for diagnostics.

    Returns
    -------
    LetExprNode
        The constructor tree, antiquotations in place.

    Raises
    ------
    QiecDiagnosticError
        If the contents do not parse as that category, or use a form the
        quoted-syntax families do not represent.
    """
    text, spliced = quoted_text(quotation, file=file)
    writer = _Writer(spliced, file, quotation.line, quotation.col)
    if family in ("SynValue", "SynType", "SynPattern") and "\n" in text:
        raise fail(
            f"a quoted {family.removeprefix('Syn').lower()} is written on one line",
            file=file,
            line=quotation.line,
            col=quotation.col,
        )
    if family == "SynDecl":
        module = _parse(text + "\n", family, quotation, file)
        if len(module.statements) + len(module.tests) != 1:
            raise fail(
                "a quoted declaration quotes exactly one declaration",
                file=file,
                line=quotation.line,
                col=quotation.col,
            )
        if module.tests:
            return writer.property(module.tests[0])
        return writer.declaration(module.statements[0])
    if family == "SynType":
        source = f"define __quoted(x : {text}) : Unit !{{}} =\n    return unit\n"
    elif family == "SynValue":
        source = f"define __quoted() : Unit !{{}} =\n    return {text}\n"
    elif family == "SynPattern":
        source = (
            "define __quoted(x : Unit) : Unit !{} =\n    case x\n"
            f"        {text} =>\n            return unit\n"
        )
    else:
        source = f"define __quoted() : Unit !{{}} =\n{textwrap.indent(text, '    ')}\n"
    (declaration,) = _parse(source, family, quotation, file).statements
    assert isinstance(declaration, QiecComputationDecl)
    if family == "SynType":
        (parameter,) = declaration.parameters
        return writer.type_(parameter.type_expr)
    if family == "SynValue":
        returned = declaration.body
        assert isinstance(returned, QiecReturnComputation)
        return writer.value(returned.value)
    if family == "SynPattern":
        case = declaration.body
        assert isinstance(case, QiecCaseComputation)
        return writer.pattern(case.branches[0].pattern)
    return writer.computation(declaration.body)

quoted_text

quoted_text(quotation: QiecQuotation, *, file: str) -> tuple[str, list[LetExprNode]]

A code quotation's contents as source text, antiquotations as names.

PARAMETER DESCRIPTION
quotation

The quotation.

TYPE: QiecQuotation

file

The file, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
tuple[str, list[LetExprNode]]

The contents, dedented (a multi-line quotation's first line, after [|, is empty), and the value each placeholder stands for.

RAISES DESCRIPTION
QiecDiagnosticError

If a multi-line quotation has content on the line of [|.

Source code in src/quivers/dsl/notation/code.py
def quoted_text(
    quotation: QiecQuotation, *, file: str
) -> tuple[str, list[LetExprNode]]:
    """A code quotation's contents as source text, antiquotations as names.

    Parameters
    ----------
    quotation : QiecQuotation
        The quotation.
    file : str
        The file, for diagnostics.

    Returns
    -------
    tuple[str, list[LetExprNode]]
        The contents, dedented (a multi-line quotation's first line, after
        ``[|``, is empty), and the value each placeholder stands for.

    Raises
    ------
    QiecDiagnosticError
        If a multi-line quotation has content on the line of ``[|``.
    """
    raw = quotation.source.encode("utf-8")
    spliced: list[LetExprNode] = []
    pieces: list[bytes] = []
    cursor = 0
    for antiquote in _antiquotes(quotation.items):
        start = antiquote.start - quotation.start
        end = antiquote.end - quotation.start
        pieces.append(raw[cursor:start])
        if antiquote.value is not None:
            spliced.append(antiquote.value)
        else:
            assert antiquote.name is not None
            spliced.append(
                LetExprVar(name=antiquote.name, line=antiquote.line, col=antiquote.col)
            )
        pieces.append(f"{_PLACEHOLDER}{len(spliced) - 1}".encode())
        cursor = end
    pieces.append(raw[cursor:])
    text = b"".join(pieces).decode("utf-8")
    inner = text.removeprefix("[|").removesuffix("|]")
    if "\n" not in inner:
        return inner.strip(), spliced
    first, rest = inner.split("\n", 1)
    if first.strip():
        raise fail(
            "a multi-line quotation starts on the line after `[|`",
            file=file,
            line=quotation.line,
            col=quotation.col,
        )
    return textwrap.dedent(rest).strip("\n").rstrip(), spliced

core_pattern

core_pattern(core: CoreNode, *, file: str, line: int, col: int) -> QiecPattern

The surface pattern of a meaning.

PARAMETER DESCRIPTION
core

The meaning of a pattern quotation.

TYPE: CoreNode

file

The file, for diagnostics.

TYPE: str

line

The quotation's location.

TYPE: int

col

The quotation's location.

TYPE: int

RETURNS DESCRIPTION
QiecPattern

A constructor pattern; a variable matches the sort's variable constructor at its index, and $x binds x.

RAISES DESCRIPTION
QiecDiagnosticError

If an antiquotation lies under a binder its author cannot see, so the matched subterm would have to be strengthened.

Source code in src/quivers/dsl/notation/elaborate.py
def core_pattern(core: CoreNode, *, file: str, line: int, col: int) -> QiecPattern:
    """The surface pattern of a meaning.

    Parameters
    ----------
    core : CoreNode
        The meaning of a pattern quotation.
    file : str
        The file, for diagnostics.
    line, col : int
        The quotation's location.

    Returns
    -------
    QiecPattern
        A constructor pattern; a variable matches the sort's variable
        constructor at its index, and ``$x`` binds ``x``.

    Raises
    ------
    QiecDiagnosticError
        If an antiquotation lies under a binder its author cannot see, so
        the matched subterm would have to be strengthened.
    """
    if isinstance(core, CoreAntiquote):
        written = core.antiquote
        if core.shifts:
            raise fail(
                f"`${written.name}` lies under a binder a notation introduces, which "
                "a pattern cannot strengthen past; match the expansion with "
                "constructor patterns",
                file=file,
                line=written.line,
                col=written.col,
            )
        assert written.name is not None
        if written.name == "_":
            return QiecWildcardPattern(line=written.line, col=written.col)
        return QiecNamePattern(name=written.name, line=written.line, col=written.col)
    if isinstance(core, CoreVariable):
        return QiecConstructorPattern(
            constructor=variable_name(core.syntax, core.sort),
            arguments=(
                QiecLiteralPattern(
                    value=LetExprLiteral(
                        value=core.index, integral=True, line=line, col=col
                    ),
                    line=line,
                    col=col,
                ),
            ),
            line=line,
            col=col,
        )
    if isinstance(core, CoreLeaf):
        value: LetExprNode = (
            LetExprString(value=core.text, line=line, col=col)
            if core.is_text
            else LetExprLiteral(value=core.number, integral=True, line=line, col=col)
        )
        return QiecLiteralPattern(value=value, line=line, col=col)
    if isinstance(core, CoreBinding):
        # A binding field holds its body in the extended scope; the bound
        # variables have no names in the host program, so the field is
        # matched directly.
        return core_pattern(core.body, file=file, line=line, col=col)
    assert isinstance(core, CoreApply)
    return QiecConstructorPattern(
        constructor=core.op,
        arguments=tuple(
            core_pattern(a, file=file, line=line, col=col) for a in core.args
        ),
        line=line,
        col=col,
    )

core_value

core_value(core: CoreNode, hoist: Hoist, *, line: int, col: int) -> LetExprNode

The surface value of a meaning.

PARAMETER DESCRIPTION
core

The meaning.

TYPE: CoreNode

hoist

Binds a splice that must be weakened.

TYPE: Hoist

line

The quotation's location, given to the nodes it becomes.

TYPE: int

col

The quotation's location, given to the nodes it becomes.

TYPE: int

RETURNS DESCRIPTION
LetExprNode

A constructor tree over the signature's families.

Source code in src/quivers/dsl/notation/elaborate.py
def core_value(core: CoreNode, hoist: Hoist, *, line: int, col: int) -> LetExprNode:
    """The surface value of a meaning.

    Parameters
    ----------
    core : CoreNode
        The meaning.
    hoist : Hoist
        Binds a splice that must be weakened.
    line, col : int
        The quotation's location, given to the nodes it becomes.

    Returns
    -------
    LetExprNode
        A constructor tree over the signature's families.
    """
    if isinstance(core, CoreAntiquote):
        value = _antiquoted(core)
        if core.shifts:
            return hoist(core, value)
        return value
    if isinstance(core, CoreVariable):
        return LetExprCall(
            func=variable_name(core.syntax, core.sort),
            args=(LetExprLiteral(value=core.index, integral=True, line=line, col=col),),
            line=line,
            col=col,
        )
    if isinstance(core, CoreLeaf):
        if core.is_text:
            return LetExprString(value=core.text, line=line, col=col)
        return LetExprLiteral(value=core.number, integral=True, line=line, col=col)
    if isinstance(core, CoreBinding):
        return core_value(core.body, hoist, line=line, col=col)
    assert isinstance(core, CoreApply)
    if not core.args:
        return LetExprVar(name=core.op, line=line, col=col)
    return LetExprCall(
        func=core.op,
        args=tuple(core_value(a, hoist, line=line, col=col) for a in core.args),
        line=line,
        col=col,
    )

describe_active

describe_active(active: Sequence[str]) -> str

The active notations for messages.

PARAMETER DESCRIPTION
active

Flat notation names.

TYPE: Sequence[str]

RETURNS DESCRIPTION
str

Each notation with its module.

Source code in src/quivers/dsl/notation/elaborate.py
def describe_active(active: Sequence[str]) -> str:
    """The active notations for messages.

    Parameters
    ----------
    active : Sequence[str]
        Flat notation names.

    Returns
    -------
    str
        Each notation with its module.
    """
    return ", ".join(describe_notation(name) for name in active)

expand_notation

expand_notation(module: Module, *, file_path: str) -> Module

Elaborate every quotation of a module and drop its notation statements.

A quotation whose module scoping already named its active notations uses them; any other reads the notations the open notation statements before it activate, in this module.

PARAMETER DESCRIPTION
module

A parsed (or flat) module.

TYPE: Module

file_path

Its file, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
Module

The module with every quotation replaced by the value or pattern it stands for, and without notation declarations or open notation statements.

RAISES DESCRIPTION
QiecDiagnosticError

If an open notation names no notation of the module, or a quotation does not elaborate.

Source code in src/quivers/dsl/notation/elaborate.py
def expand_notation(module: Module, *, file_path: str) -> Module:
    """Elaborate every quotation of a module and drop its notation statements.

    A quotation whose module scoping already named its active notations
    uses them; any other reads the notations the ``open notation``
    statements before it activate, in this module.

    Parameters
    ----------
    module : Module
        A parsed (or flat) module.
    file_path : str
        Its file, for diagnostics.

    Returns
    -------
    Module
        The module with every quotation replaced by the value or pattern it
        stands for, and without notation declarations or ``open
        notation`` statements.

    Raises
    ------
    QiecDiagnosticError
        If an ``open notation`` names no notation of the module, or a
        quotation does not elaborate.
    """
    if not has_notation_surface(module):
        return module
    program = notation_program(module.statements, file=file_path)
    active: tuple[str, ...] = ()
    opened_at = (0, 0)
    statements: list[Statement] = []
    for statement in module.statements:
        if isinstance(statement, OpenNotationDecl):
            targets = statement.notations or (statement.target,)
            for target in targets:
                if target not in program.notations:
                    raise fail(
                        f"`{statement.target}` names no notation of this module",
                        file=file_path,
                        line=statement.line,
                        col=statement.col,
                    )
                if target not in active:
                    active = (*active, target)
            opened_at = (statement.line, statement.col)
            continue
        if isinstance(statement, NameSpellingsDecl):
            continue
        if isinstance(statement, NotationDecl):
            program.table(
                (statement.name,),
                file=file_path,
                line=statement.line,
                col=statement.col,
            )
            continue
        statements.append(
            _Rewriter(program, active, file=file_path).statement(statement)
        )
    tests: list[TestDecl] = []
    for test in module.tests:
        rewriter = _Rewriter(program, active, file=file_path)
        sink: list[tuple[str, QiecCallComputation]] = []
        rewritten = rewriter.node(test, sink)
        if sink:
            rewriter.refuse_hoist(sink)
        assert isinstance(rewritten, TestDecl)
        tests.append(rewritten)
    line, col = opened_at
    printers = (
        printer_statements(
            program.table(active, file=file_path, line=line, col=col),
            line=line,
            col=col,
        )
        if active
        else ()
    )
    return module.with_(statements=(*statements, *printers), tests=tuple(tests))

has_notation_surface

has_notation_surface(module: Module) -> bool

Whether a module declares, opens, or quotes notation.

PARAMETER DESCRIPTION
module

A parsed module.

TYPE: Module

RETURNS DESCRIPTION
bool

True when some statement or test holds notation surface.

Source code in src/quivers/dsl/notation/elaborate.py
def has_notation_surface(module: Module) -> bool:
    """Whether a module declares, opens, or quotes notation.

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

    Returns
    -------
    bool
        True when some statement or test holds notation surface.
    """
    pending: list[SyntaxValue] = [*module.statements, *module.tests]
    while pending:
        node = pending.pop()
        if isinstance(
            node,
            NotationDecl
            | OpenNotationDecl
            | NameSpellingsDecl
            | QiecQuotation
            | QiecQuotationPattern,
        ):
            return True
        if isinstance(node, tuple):
            pending.extend(node)
        elif isinstance(node, dx.Model):
            pending.extend(getattr(node, name) for name in type(node).__field_specs__)
    return False

name_spellings

name_spellings(module: Module) -> tuple[NameSpelling, ...]

The root module's spellings of imported names a flat program records.

PARAMETER DESCRIPTION
module

A flat program.

TYPE: Module

RETURNS DESCRIPTION
tuple[NameSpelling, ...]

Its spellings, or none for a program read from one module.

Source code in src/quivers/dsl/notation/elaborate.py
def name_spellings(module: Module) -> tuple[NameSpelling, ...]:
    """The root module's spellings of imported names a flat program records.

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

    Returns
    -------
    tuple[NameSpelling, ...]
        Its spellings, or none for a program read from one module.
    """
    return tuple(
        entry
        for statement in module.statements
        if isinstance(statement, NameSpellingsDecl)
        for entry in statement.entries
    )

notation_program

notation_program(statements: Sequence[Statement], files: Mapping[str, str] | None = None, *, file: str) -> NotationProgram

The notations and signatures a program declares.

PARAMETER DESCRIPTION
statements

The program's statements.

TYPE: Sequence[Statement]

files

The file each notation is declared in; file for every notation not listed.

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

file

The program's file.

TYPE: str

RETURNS DESCRIPTION
NotationProgram

Its notations and signatures.

Source code in src/quivers/dsl/notation/elaborate.py
def notation_program(
    statements: Sequence[Statement],
    files: Mapping[str, str] | None = None,
    *,
    file: str,
) -> NotationProgram:
    """The notations and signatures a program declares.

    Parameters
    ----------
    statements : Sequence[Statement]
        The program's statements.
    files : Mapping[str, str] | None
        The file each notation is declared in; ``file`` for every notation
        not listed.
    file : str
        The program's file.

    Returns
    -------
    NotationProgram
        Its notations and signatures.
    """
    from_files = dict(files or {})
    notations: dict[str, NotationDecl] = {}
    syntaxes: dict[str, SyntaxInfo] = {}
    for statement in statements:
        if isinstance(statement, NotationDecl):
            notations[statement.name] = statement
            from_files.setdefault(statement.name, file)
        elif isinstance(statement, SyntaxDecl):
            syntaxes[statement.name] = SyntaxInfo(
                name=statement.name, signature=_signature_from_declaration(statement)
            )
    return NotationProgram(notations, syntaxes, from_files)

parse_quotation

parse_quotation(text: str) -> QiecQuotation

Read the text of a quotation's contents into its token tree.

PARAMETER DESCRIPTION
text

What stands between [| and |], on one line.

TYPE: str

RETURNS DESCRIPTION
QiecQuotation

The quotation, unscoped.

RAISES DESCRIPTION
ParseError

If the text is not a token tree.

Source code in src/quivers/dsl/notation/elaborate.py
def parse_quotation(text: str) -> QiecQuotation:
    """Read the text of a quotation's contents into its token tree.

    Parameters
    ----------
    text : str
        What stands between ``[|`` and ``|]``, on one line.

    Returns
    -------
    QiecQuotation
        The quotation, unscoped.

    Raises
    ------
    ParseError
        If the text is not a token tree.
    """
    module = parse(f"define __quoted() : Unit !{{}} =\n    return [| {text} |]\n")
    (declaration,) = module.statements
    assert isinstance(declaration, QiecComputationDecl)
    body = declaration.body
    assert isinstance(body, QiecReturnComputation)
    assert isinstance(body.value, QiecQuotation)
    return body.value

quote

quote(program: NotationProgram, active: tuple[str, ...], text: str, *, sort: SortKey = None, file: str = '<quotation>') -> Quoted

Read and expand the contents of a quotation.

PARAMETER DESCRIPTION
program

The program's notations and signatures.

TYPE: NotationProgram

active

The flat names of the active notations.

TYPE: tuple[str, ...]

text

The quotation's contents.

TYPE: str

sort

The sort it must build, if known.

TYPE: SortKey DEFAULT: None

file

The file, for diagnostics.

TYPE: str DEFAULT: '<quotation>'

RETURNS DESCRIPTION
Quoted

Its meaning and sort.

Source code in src/quivers/dsl/notation/elaborate.py
def quote(
    program: NotationProgram,
    active: tuple[str, ...],
    text: str,
    *,
    sort: SortKey = None,
    file: str = "<quotation>",
) -> Quoted:
    """Read and expand the contents of a quotation.

    Parameters
    ----------
    program : NotationProgram
        The program's notations and signatures.
    active : tuple[str, ...]
        The flat names of the active notations.
    text : str
        The quotation's contents.
    sort : SortKey
        The sort it must build, if known.
    file : str
        The file, for diagnostics.

    Returns
    -------
    Quoted
        Its meaning and sort.
    """
    return read_quoted(parse_quotation(text), program, active, sort, file=file)

read_quoted

read_quoted(quotation: QiecQuotation | QiecQuotationPattern, program: NotationProgram, active: tuple[str, ...], expected: SortKey, *, file: str) -> Quoted

Read and expand one quotation.

PARAMETER DESCRIPTION
quotation

The quotation.

TYPE: QiecQuotation | QiecQuotationPattern

program

The program's notations.

TYPE: NotationProgram

active

The notations active where it stands.

TYPE: tuple[str, ...]

expected

The sort an annotation gives it, if any.

TYPE: SortKey

file

The file, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
Quoted

Its meaning and sort.

RAISES DESCRIPTION
QiecDiagnosticError

If it does not read, reads two ways, does not resolve, or its sort is decided by nothing.

Source code in src/quivers/dsl/notation/elaborate.py
def read_quoted(
    quotation: QiecQuotation | QiecQuotationPattern,
    program: NotationProgram,
    active: tuple[str, ...],
    expected: SortKey,
    *,
    file: str,
) -> Quoted:
    """Read and expand one quotation.

    Parameters
    ----------
    quotation : QiecQuotation | QiecQuotationPattern
        The quotation.
    program : NotationProgram
        The program's notations.
    active : tuple[str, ...]
        The notations active where it stands.
    expected : SortKey
        The sort an annotation gives it, if any.
    file : str
        The file, for diagnostics.

    Returns
    -------
    Quoted
        Its meaning and sort.

    Raises
    ------
    QiecDiagnosticError
        If it does not read, reads two ways, does not resolve, or its sort
        is decided by nothing.
    """
    table = program.table(active, file=file, line=quotation.line, col=quotation.col)
    text = read_quotation(quotation.items, table, file=file)
    reading = enforest(
        text.tokens, table, expected, file=file, line=quotation.line, col=quotation.col
    )
    context = tuple(name.text for name in text.context)
    if reading.sort:
        info = table.syntax(reading.syntax)
        sort = reading.sort
    elif expected is not None:
        info = table.syntax(expected[0])
        sort = expected[1]
    elif isinstance(reading.node, ParseAntiquote) and not context:
        return Quoted(
            core=CoreAntiquote(
                antiquote=reading.node.token.antiquote, syntax="", sort=""
            ),
            context=context,
            reading=reading,
        )
    else:
        candidates = [
            (info, sort)
            for info in table.syntaxes
            for sort in sorted(variable_sorts(info))
        ]
        if isinstance(reading.node, ParseName):
            name = reading.node.token.text
            constants = [
                (table.syntax(info.name), constructor.codomain)
                for info in table.syntaxes
                for constructor in info.signature.constructors_t
                if not constructor.arity and split_module(constructor.name)[1] == name
            ]
            if constants and name not in context:
                candidates = constants
        if len(candidates) != 1:
            raise fail(
                "nothing in the quotation decides its sort; annotate it, as in "
                "`([| ... |] : Sig.S)`",
                file=file,
                line=quotation.line,
                col=quotation.col,
            )
        info, sort = candidates[0]
    core = expand_reading(reading.node, table, info, sort, text.context, file=file)
    return Quoted(
        core=core, syntax=info.name, sort=sort, context=context, reading=reading
    )

render_core

render_core(core: CoreNode) -> str

The surface text of a quotation's meaning.

PARAMETER DESCRIPTION
core

The meaning.

TYPE: CoreNode

RETURNS DESCRIPTION
str

Its constructor tree, each variable written Sig.S.var(i), each splice $x (or $(...)), weakened by Sig.S.shift.

Source code in src/quivers/dsl/notation/elaborate.py
def render_core(core: CoreNode) -> str:
    """The surface text of a quotation's meaning.

    Parameters
    ----------
    core : CoreNode
        The meaning.

    Returns
    -------
    str
        Its constructor tree, each variable written ``Sig.S.var(i)``, each
        splice ``$x`` (or ``$(...)``), weakened by ``Sig.S.shift``.
    """
    if isinstance(core, CoreAntiquote):
        written = core.antiquote
        text = f"${written.name}" if written.name is not None else "$(...)"
        for step in core.shifts:
            shift = member_name(family_name(core.syntax, core.sort), "shift")
            text = f"{_local_name(shift)}({text}, {step.cutoff}, {step.amount})"
        return text
    if isinstance(core, CoreVariable):
        return f"{_local_name(variable_name(core.syntax, core.sort))}({core.index})"
    if isinstance(core, CoreLeaf):
        return f'"{core.text}"' if core.is_text else str(core.number)
    if isinstance(core, CoreBinding):
        return render_core(core.body)
    assert isinstance(core, CoreApply)
    head = _local_name(core.op)
    if not core.args:
        return head
    return f"{head}({', '.join(render_core(a) for a in core.args)})"

scope_local_notation

scope_local_notation(module: Module) -> Module

Record on each quotation the notations its own module has opened.

A module read alone (no module graph) opens only its own notations; each quotation records the ones open notation statements before it activate, as module scoping does for a graph.

PARAMETER DESCRIPTION
module

A parsed module.

TYPE: Module

RETURNS DESCRIPTION
Module

The module, every quotation scoped.

Source code in src/quivers/dsl/notation/elaborate.py
def scope_local_notation(module: Module) -> Module:
    """Record on each quotation the notations its own module has opened.

    A module read alone (no module graph) opens only its own notations;
    each quotation records the ones ``open notation`` statements before it
    activate, as module scoping does for a graph.

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

    Returns
    -------
    Module
        The module, every quotation scoped.
    """
    if not has_notation_surface(module):
        return module
    active: tuple[str, ...] = ()
    statements: list[Statement] = []
    for statement in module.statements:
        if isinstance(statement, OpenNotationDecl):
            targets = statement.notations or (statement.target,)
            active = (*active, *(name for name in targets if name not in active))
            statements.append(statement)
            continue
        scoped = _scope(statement, active)
        assert isinstance(scoped, Statement)
        statements.append(scoped)
    return module.with_(statements=tuple(statements))

node_key

node_key(node: ParseNode) -> ReadingKey

A structural key of a reading, for telling readings apart.

PARAMETER DESCRIPTION
node

The reading.

TYPE: ParseNode

RETURNS DESCRIPTION
ReadingKey

Equal for equal readings.

Source code in src/quivers/dsl/notation/enforest.py
def node_key(node: ParseNode) -> ReadingKey:
    """A structural key of a reading, for telling readings apart.

    Parameters
    ----------
    node : ParseNode
        The reading.

    Returns
    -------
    ReadingKey
        Equal for equal readings.
    """
    if isinstance(node, ParseUse):
        return (
            "use",
            node.production,
            tuple(_fill_key(fill) for fill in node.fills),
        )
    if isinstance(node, ParseName):
        return ("name", node.token.text, node.token.start)
    if isinstance(node, ParseAntiquote):
        return ("anti", node.token.start)
    assert isinstance(node, ParseConstructor)
    return ("ctor", node.op, tuple(_argument_key(a) for a in node.args))

production_of

production_of(use: ParseUse, table: NotationTable) -> Production

The production a use applies.

PARAMETER DESCRIPTION
use

The use.

TYPE: ParseUse

table

The active notations.

TYPE: NotationTable

RETURNS DESCRIPTION
Production

Its production.

Source code in src/quivers/dsl/notation/enforest.py
def production_of(use: ParseUse, table: NotationTable) -> Production:
    """The production a use applies.

    Parameters
    ----------
    use : ParseUse
        The use.
    table : NotationTable
        The active notations.

    Returns
    -------
    Production
        Its production.
    """
    return _production(use.production, table)

core_term

core_term(node: CoreNode) -> Term

The host term of a nameless term that splices nothing.

PARAMETER DESCRIPTION
node

The term.

TYPE: CoreNode

RETURNS DESCRIPTION
Term

The structural term, BoundVar(i) for a variable.

RAISES DESCRIPTION
ValueError

If the term splices an antiquotation, whose value is not known.

Source code in src/quivers/dsl/notation/hygiene.py
def core_term(node: CoreNode) -> Term:
    """The host term of a nameless term that splices nothing.

    Parameters
    ----------
    node : CoreNode
        The term.

    Returns
    -------
    Term
        The structural term, ``BoundVar(i)`` for a variable.

    Raises
    ------
    ValueError
        If the term splices an antiquotation, whose value is not known.
    """
    if isinstance(node, CoreVariable):
        return Term(op=BOUND_VAR, args=(node.index,))
    if isinstance(node, CoreApply):
        args: list[Term | str | int] = []
        for argument in node.args:
            if isinstance(argument, CoreBinding):
                args.append(core_term(argument.body))
            elif isinstance(argument, CoreLeaf):
                args.append(argument.text if argument.is_text else argument.number)
            else:
                args.append(core_term(argument))
        return Term(op=node.op, args=tuple(args))
    if isinstance(node, CoreAntiquote):
        raise ValueError("a term that splices an antiquotation has no host value")
    raise ValueError(f"{node.kind} is not a term")

definition_scope

definition_scope(notation: str) -> int

The scope every name a notation's templates introduce carries.

PARAMETER DESCRIPTION
notation

The notation's flat name.

TYPE: str

RETURNS DESCRIPTION
int

Its definition scope.

Source code in src/quivers/dsl/notation/hygiene.py
def definition_scope(notation: str) -> int:
    """The scope every name a notation's templates introduce carries.

    Parameters
    ----------
    notation : str
        The notation's flat name.

    Returns
    -------
    int
        Its definition scope.
    """
    scope = _DEFINITION_SCOPES.get(notation)
    if scope is None:
        scope = fresh_scope()
        _DEFINITION_SCOPES[notation] = scope
    return scope

expand_reading

expand_reading(node: ParseNode, table: NotationTable, info: SyntaxInfo, sort: str, context: Sequence[TokenName], *, file: str) -> CoreNode

The nameless term a reading means.

PARAMETER DESCRIPTION
node

The reading.

TYPE: ParseNode

table

The active notations.

TYPE: NotationTable

info

The signature of the quoted sort.

TYPE: SyntaxInfo

sort

The quoted sort.

TYPE: str

context

The quotation's context names, outermost first.

TYPE: Sequence[TokenName]

file

The file, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
CoreNode

The de Bruijn term.

RAISES DESCRIPTION
QiecDiagnosticError

If a name is unbound, a variable has the wrong sort, or a literal or an abstraction stands where a term is expected.

Source code in src/quivers/dsl/notation/hygiene.py
def expand_reading(
    node: ParseNode,
    table: NotationTable,
    info: SyntaxInfo,
    sort: str,
    context: Sequence[TokenName],
    *,
    file: str,
) -> CoreNode:
    """The nameless term a reading means.

    Parameters
    ----------
    node : ParseNode
        The reading.
    table : NotationTable
        The active notations.
    info : SyntaxInfo
        The signature of the quoted sort.
    sort : str
        The quoted sort.
    context : Sequence[TokenName]
        The quotation's context names, outermost first.
    file : str
        The file, for diagnostics.

    Returns
    -------
    CoreNode
        The de Bruijn term.

    Raises
    ------
    QiecDiagnosticError
        If a name is unbound, a variable has the wrong sort, or a literal
        or an abstraction stands where a term is expected.
    """
    use_scope = fresh_scope()
    syntax = _Expander(table, use_scope).expand(node)
    return _Resolver(table, context, use_scope, file=file).resolve(
        syntax, info, sort, (), frozenset()
    )

fresh_scope

fresh_scope() -> int

A scope no name carries yet.

RETURNS DESCRIPTION
int

The scope.

Source code in src/quivers/dsl/notation/hygiene.py
def fresh_scope() -> int:
    """A scope no name carries yet.

    Returns
    -------
    int
        The scope.
    """
    return next(_SCOPES)

variable_sorts

variable_sorts(info: SyntaxInfo) -> frozenset[str]

The sorts some constructor of a signature binds variables of.

PARAMETER DESCRIPTION
info

The signature.

TYPE: SyntaxInfo

RETURNS DESCRIPTION
frozenset[str]

The sorts that have variables.

Source code in src/quivers/dsl/notation/hygiene.py
def variable_sorts(info: SyntaxInfo) -> frozenset[str]:
    """The sorts some constructor of a signature binds variables of.

    Parameters
    ----------
    info : SyntaxInfo
        The signature.

    Returns
    -------
    frozenset[str]
        The sorts that have variables.
    """
    return frozenset(
        variable.sort
        for constructor in info.signature.constructors_t
        for scope in constructor.scopes
        for variable in scope
    )

binder_levels

binder_levels(template: TemplateNode, holes: frozenset[str]) -> dict[str, int]

How many binder holes enclose each binder hole of a template.

PARAMETER DESCRIPTION
template

A production's template.

TYPE: TemplateNode

holes

Its binder holes.

TYPE: frozenset[str]

RETURNS DESCRIPTION
dict[str, int]

For each binder hole, the binder holes of abstractions around it.

Source code in src/quivers/dsl/notation/printing.py
def binder_levels(template: TemplateNode, holes: frozenset[str]) -> dict[str, int]:
    """How many binder holes enclose each binder hole of a template.

    Parameters
    ----------
    template : TemplateNode
        A production's template.
    holes : frozenset[str]
        Its binder holes.

    Returns
    -------
    dict[str, int]
        For each binder hole, the binder holes of abstractions around it.
    """
    found: dict[str, int] = {}

    def visit(node: TemplateNode, outside: int) -> None:
        if isinstance(node, TemplateApply):
            for argument in node.args:
                visit(argument, outside)
        elif isinstance(node, TemplateAbstraction):
            inner = outside
            for name in node.names:
                if name in holes:
                    found[name] = inner
                    inner += 1
            visit(node.body, inner)

    visit(template, 0)
    return found

print_term

print_term(term: Term, table: NotationTable, syntax: str, sort: str, context: Sequence[str] = (), *, naming: Literal['fresh', 'level'] = 'fresh') -> str

The text of a term in the active notations.

PARAMETER DESCRIPTION
term

The de Bruijn term.

TYPE: Term

table

The active notations.

TYPE: NotationTable

syntax

The flat name of the term's signature.

TYPE: str

sort

The term's sort.

TYPE: str

context

Names of the term's free variables, outermost first. When it is not empty the text starts with the quotation context x, y ⊢.

TYPE: Sequence[str] DEFAULT: ()

naming

"fresh" names a bound variable by its binder hole, renamed apart from every name in scope; "level" names it x followed by its de Bruijn level, as the generated Show instances do.

TYPE: Literal['fresh', 'level'] DEFAULT: 'fresh'

RETURNS DESCRIPTION
str

The text, which a quotation reads back to the same term.

Source code in src/quivers/dsl/notation/printing.py
def print_term(
    term: Term,
    table: NotationTable,
    syntax: str,
    sort: str,
    context: Sequence[str] = (),
    *,
    naming: Literal["fresh", "level"] = "fresh",
) -> str:
    """The text of a term in the active notations.

    Parameters
    ----------
    term : Term
        The de Bruijn term.
    table : NotationTable
        The active notations.
    syntax : str
        The flat name of the term's signature.
    sort : str
        The term's sort.
    context : Sequence[str]
        Names of the term's free variables, outermost first. When it is
        not empty the text starts with the quotation context ``x, y ⊢``.
    naming : Literal["fresh", "level"]
        ``"fresh"`` names a bound variable by its binder hole, renamed
        apart from every name in scope; ``"level"`` names it ``x`` followed
        by its de Bruijn level, as the generated ``Show`` instances do.

    Returns
    -------
    str
        The text, which a quotation reads back to the same term.
    """
    info = table.syntax(syntax)
    printer = _Printer(table, level=naming == "level")
    printed = printer.print(term, info, sort, tuple(context)).text
    if context:
        return f"{', '.join(context)} ⊢ {printed}"
    return printed

printable_sorts

printable_sorts(table: NotationTable) -> frozenset[tuple[str, str]]

The signature sorts some active production builds or binds.

PARAMETER DESCRIPTION
table

The active notations.

TYPE: NotationTable

RETURNS DESCRIPTION
frozenset[tuple[str, str]]

Each signature's flat name with one of its sorts.

Source code in src/quivers/dsl/notation/printing.py
def printable_sorts(table: NotationTable) -> frozenset[tuple[str, str]]:
    """The signature sorts some active production builds or binds.

    Parameters
    ----------
    table : NotationTable
        The active notations.

    Returns
    -------
    frozenset[tuple[str, str]]
        Each signature's flat name with one of its sorts.
    """
    found = {(production.syntax, production.sort) for production in table.productions}
    for info in table.syntaxes:
        found |= {(info.name, sort) for sort in variable_sorts(info)}
    return frozenset(found)

shown_value

shown_value(module: QiecModule, value: RuntimeConstructor) -> str | None

A value printed by its family's Show instance, when it has one.

PARAMETER DESCRIPTION
module

The checked module the value belongs to.

TYPE: QiecModule

value

A family value of the reference machine.

TYPE: RuntimeConstructor

RETURNS DESCRIPTION
str | None

The instance's text, or None when the value's family declares no show taking just the value.

Source code in src/quivers/dsl/notation/rendering.py
def shown_value(module: QiecModule, value: RuntimeConstructor) -> str | None:
    """A value printed by its family's ``Show`` instance, when it has one.

    Parameters
    ----------
    module : QiecModule
        The checked module the value belongs to.
    value : RuntimeConstructor
        A family value of the reference machine.

    Returns
    -------
    str | None
        The instance's text, or ``None`` when the value's family declares
        no ``show`` taking just the value.
    """
    result = value.result_type
    if not isinstance(result, TypeApplication) or result.arguments:
        return None
    name = member_name(result.constructor.name, SHOW_MEMBER)
    computation = next((c for c in module.computations if c.name == name), None)
    if computation is None or len(computation.parameters) != 1 or computation.telescope:
        return None
    shown = run_named(module, name, (value,)).value
    return shown if isinstance(shown, str) else None

scope_module_notation

scope_module_notation(statements: Sequence[Statement], tests: Sequence[TestDecl], resolver: ModuleNotations) -> tuple[tuple[Statement, ...], tuple[TestDecl, ...]]

Scope one module's notation statements and quotations.

PARAMETER DESCRIPTION
statements

The module's walked statements, in order.

TYPE: Sequence[Statement]

tests

Its tests, which see the notations active at the end of the module.

TYPE: Sequence[TestDecl]

resolver

Resolves the module's notation references.

TYPE: ModuleNotations

RETURNS DESCRIPTION
tuple[tuple[Statement, ...], tuple[TestDecl, ...]]

The statements, each open notation naming its notations, each relation naming other notations' productions by flat name, and each quotation naming the notations active where it stands; and the tests, scoped likewise.

Source code in src/quivers/dsl/notation/scoping.py
def scope_module_notation(
    statements: Sequence[Statement],
    tests: Sequence[TestDecl],
    resolver: ModuleNotations,
) -> tuple[tuple[Statement, ...], tuple[TestDecl, ...]]:
    """Scope one module's notation statements and quotations.

    Parameters
    ----------
    statements : Sequence[Statement]
        The module's walked statements, in order.
    tests : Sequence[TestDecl]
        Its tests, which see the notations active at the end of the module.
    resolver : ModuleNotations
        Resolves the module's notation references.

    Returns
    -------
    tuple[tuple[Statement, ...], tuple[TestDecl, ...]]
        The statements, each ``open notation`` naming its notations, each
        relation naming other notations' productions by flat name, and
        each quotation naming the notations active where it stands; and
        the tests, scoped likewise.
    """
    active: tuple[str, ...] = ()
    scoped: list[Statement] = []
    for statement in statements:
        if isinstance(statement, OpenNotationDecl):
            found = resolver.resolve(statement.target, statement.line, statement.col)
            active = (*active, *(name for name in found if name not in active))
            scoped.append(statement.with_(notations=found))
            continue
        if isinstance(statement, NotationDecl):
            scoped.append(
                statement.with_(
                    relations=tuple(
                        resolver.relation(statement, relation)
                        for relation in statement.relations
                    )
                )
            )
            continue
        scoped.append(scope_statement(statement, active))
    scoped_tests = [scope_test(test, active) for test in tests]
    return tuple(scoped), tuple(scoped_tests)

scope_statement

scope_statement(statement: Statement, active: tuple[str, ...]) -> Statement

A statement with the active notations recorded on its quotations.

PARAMETER DESCRIPTION
statement

A statement of a module or of a module body.

TYPE: Statement

active

The flat names of the notations active where it stands.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
Statement

The statement, each quotation (value or pattern) naming active.

Source code in src/quivers/dsl/notation/scoping.py
def scope_statement(statement: Statement, active: tuple[str, ...]) -> Statement:
    """A statement with the active notations recorded on its quotations.

    Parameters
    ----------
    statement : Statement
        A statement of a module or of a module body.
    active : tuple[str, ...]
        The flat names of the notations active where it stands.

    Returns
    -------
    Statement
        The statement, each quotation (value or pattern) naming ``active``.
    """
    result = _scope_quotations(statement, active)
    assert isinstance(result, Statement)
    return result

scope_test

scope_test(test: TestDecl, active: tuple[str, ...]) -> TestDecl

A test with the active notations recorded on its quotations.

PARAMETER DESCRIPTION
test

A test, property, or example declaration.

TYPE: TestDecl

active

The flat names of the notations active at the end of its module.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
TestDecl

The declaration, each quotation naming active.

Source code in src/quivers/dsl/notation/scoping.py
def scope_test(test: TestDecl, active: tuple[str, ...]) -> TestDecl:
    """A test with the active notations recorded on its quotations.

    Parameters
    ----------
    test : TestDecl
        A ``test``, ``property``, or ``example`` declaration.
    active : tuple[str, ...]
        The flat names of the notations active at the end of its module.

    Returns
    -------
    TestDecl
        The declaration, each quotation naming ``active``.
    """
    result = _scope_quotations(test, active)
    assert isinstance(result, TestDecl)
    return result

printer_statements

printer_statements(table: NotationTable, *, line: int, col: int) -> tuple[Statement, ...]

The generated Show instances of the sorts a table covers.

PARAMETER DESCRIPTION
table

The program's active notations at the end of its root module.

TYPE: NotationTable

line

Where the open notation statement that completed the table stands; every generated node is located there, so a diagnostic about the instances points at the source that asked for them.

TYPE: int

col

Where the open notation statement that completed the table stands; every generated node is located there, so a diagnostic about the instances points at the source that asked for them.

TYPE: int

RETURNS DESCRIPTION
tuple[Statement, ...]

The computations, Sig.S.show for every object sort of every signature the table covers, and their helpers.

Source code in src/quivers/dsl/notation/show.py
def printer_statements(
    table: NotationTable, *, line: int, col: int
) -> tuple[Statement, ...]:
    """The generated ``Show`` instances of the sorts a table covers.

    Parameters
    ----------
    table : NotationTable
        The program's active notations at the end of its root module.
    line, col : int
        Where the ``open notation`` statement that completed the table
        stands; every generated node is located there, so a diagnostic
        about the instances points at the source that asked for them.

    Returns
    -------
    tuple[Statement, ...]
        The computations, ``Sig.S.show`` for every object sort of every
        signature the table covers, and their helpers.
    """
    generator = _Generator(table)
    source = generator.source()
    module = parse(source, file_path="<notation printer>")
    flat = {**generator.names.flat, _QUOTE_TEXT: '"'}
    return tuple(
        _relocate(_rename(statement, flat), line, col)
        for statement in module.statements
    )

build_table

build_table(notations: Sequence[str], declarations: Mapping[str, NotationDecl], syntaxes: Mapping[str, SyntaxInfo], files: Mapping[str, str], *, file: str, line: int = 0, col: int = 0) -> NotationTable

Read the active notations into one table.

PARAMETER DESCRIPTION
notations

The flat names of the active notations, in activation order.

TYPE: Sequence[str]

declarations

Every notation declaration of the program, by flat name. A relation's references are qualified production names (notation.production) or bare names of its own productions.

TYPE: Mapping[str, NotationDecl]

syntaxes

Every signature, by flat name.

TYPE: Mapping[str, SyntaxInfo]

files

The file each notation is declared in, by flat name.

TYPE: Mapping[str, str]

file

The file of the point the table serves, for activation refusals.

TYPE: str

line

The location of that point.

TYPE: int DEFAULT: 0

col

The location of that point.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
NotationTable

The productions, levels, and signatures.

RAISES DESCRIPTION
QiecDiagnosticError

If a notation's signature is unknown, a production does not read, two active productions have one shape, a relation names an unknown production, the relations form a cycle, or one level mixes associativities.

Source code in src/quivers/dsl/notation/table.py
def build_table(
    notations: Sequence[str],
    declarations: Mapping[str, NotationDecl],
    syntaxes: Mapping[str, SyntaxInfo],
    files: Mapping[str, str],
    *,
    file: str,
    line: int = 0,
    col: int = 0,
) -> NotationTable:
    """Read the active notations into one table.

    Parameters
    ----------
    notations : Sequence[str]
        The flat names of the active notations, in activation order.
    declarations : Mapping[str, NotationDecl]
        Every notation declaration of the program, by flat name. A
        relation's references are qualified production names
        (``notation.production``) or bare names of its own productions.
    syntaxes : Mapping[str, SyntaxInfo]
        Every signature, by flat name.
    files : Mapping[str, str]
        The file each notation is declared in, by flat name.
    file : str
        The file of the point the table serves, for activation refusals.
    line, col : int
        The location of that point.

    Returns
    -------
    NotationTable
        The productions, levels, and signatures.

    Raises
    ------
    QiecDiagnosticError
        If a notation's signature is unknown, a production does not read,
        two active productions have one shape, a relation names an unknown
        production, the relations form a cycle, or one level mixes
        associativities.
    """
    productions: list[Production] = []
    used: dict[str, SyntaxInfo] = {}
    for flat in notations:
        declaration = declarations[flat]
        where = files.get(flat, file)
        info = syntaxes.get(declaration.syntax)
        if info is None:
            raise fail(
                f"{describe_notation(flat)} is for `{declaration.syntax}`, which is "
                "not a binding signature (`syntax` declaration)",
                file=where,
                line=declaration.line,
                col=declaration.col,
            )
        used[info.name] = info
        names: set[str] = set()
        for production in declaration.productions:
            if production.name in names:
                raise fail(
                    f"{describe_notation(flat)} declares production "
                    f"`{production.name}` twice",
                    file=where,
                    line=production.line,
                    col=production.col,
                )
            names.add(production.name)
            productions.append(
                read_production(
                    flat, production, info, file=where, order=len(productions)
                )
            )
    shapes: dict[tuple[str, ...], Production] = {}
    for production in productions:
        other = shapes.get(production.shape_key)
        if other is not None:
            raise fail(
                f"{production.label} and {other.label} read the same text; activate "
                "one of them",
                file=file,
                line=line,
                col=col,
            )
        shapes[production.shape_key] = production
    index = {p.qualified: i for i, p in enumerate(productions)}
    parent = list(range(len(productions)))

    def find(i: int) -> int:
        while parent[i] != i:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i

    edges: list[tuple[int, int]] = []
    for flat in notations:
        declaration = declarations[flat]
        where = files.get(flat, file)
        local = frozenset(p.name for p in declaration.productions)
        for relation in declaration.relations:
            left = _qualified_reference(relation.left, flat, local)
            right = _qualified_reference(relation.right, flat, local)
            missing = _missing_reference(left, right, index, declarations)
            if missing is not None:
                raise fail(
                    f"{describe_notation(flat)} relates `{missing}`, which names no "
                    "production",
                    file=where,
                    line=relation.line,
                    col=relation.col,
                )
            if left not in index or right not in index:
                # A relation with a production of an inactive notation
                # orders nothing here.
                continue
            if relation.relation == "=":
                parent[find(index[left])] = find(index[right])
            else:
                edges.append((index[left], index[right]))
    roots = sorted({find(i) for i in range(len(productions))})
    level_number = {root: n for n, root in enumerate(roots)}
    level_of = tuple(level_number[find(i)] for i in range(len(productions)))
    looser_to_tighter: dict[int, set[int]] = {n: set() for n in range(len(roots))}
    for tight, loose in edges:
        a, b = level_of[tight], level_of[loose]
        if a == b:
            production = productions[tight]
            raise fail(
                f"{production.label} is related both `=` and `>` to "
                f"{productions[loose].label}",
                file=production.file,
                line=production.line,
                col=production.col,
            )
        looser_to_tighter[b].add(a)
    closure: dict[int, set[int]] = {}

    def tighter_than(level: int, path: tuple[int, ...]) -> set[int]:
        if level in path:
            members = [
                productions[i].label
                for i in range(len(productions))
                if level_of[i] == level
            ]
            first = next(i for i in range(len(productions)) if level_of[i] == level)
            raise fail(
                f"the precedence relations form a cycle through {members[0]}",
                file=productions[first].file,
                line=productions[first].line,
                col=productions[first].col,
            )
        if level in closure:
            return closure[level]
        found: set[int] = set()
        for nearer in looser_to_tighter[level]:
            found.add(nearer)
            found |= tighter_than(nearer, (*path, level))
        closure[level] = found
        return found

    levels: list[Level] = []
    for number in range(len(roots)):
        members = tuple(
            productions[i].qualified
            for i in range(len(productions))
            if level_of[i] == number
        )
        levels.append(
            Level(members=members, tighter=tuple(sorted(tighter_than(number, ()))))
        )
        members_of = [p for i, p in enumerate(productions) if level_of[i] == number]
        sides = {side for side in map(_side, members_of) if side is not None}
        lone = (
            any(p.fixity == "infix" and p.assoc == "none" for p in members_of)
            and len(members_of) > 1
        )
        if len(sides) > 1 or lone:
            first = members_of[0]
            raise fail(
                f"{first.label} shares a precedence level with productions that "
                "associate differently; give every production of one level the "
                "same associativity, and a non-associative production a level "
                "of its own",
                file=first.file,
                line=first.line,
                col=first.col,
            )
    return NotationTable(
        notations=tuple(notations),
        productions=tuple(productions),
        levels=tuple(levels),
        level_of=level_of,
        syntaxes=tuple(used.values()),
    )

describe_notation

describe_notation(flat: str) -> str

A notation named with its module, for messages.

PARAMETER DESCRIPTION
flat

The notation's flat-program name.

TYPE: str

RETURNS DESCRIPTION
str

notation N of module m.

Source code in src/quivers/dsl/notation/table.py
def describe_notation(flat: str) -> str:
    """A notation named with its module, for messages.

    Parameters
    ----------
    flat : str
        The notation's flat-program name.

    Returns
    -------
    str
        ``notation N of module m``.
    """
    _, local = split_module(flat)
    return f"notation {local} of {notation_module(flat)}"

fail

fail(message: str, *, file: str, line: int = 0, col: int = 0) -> QiecDiagnosticError

A located notation diagnostic.

PARAMETER DESCRIPTION
message

What was refused.

TYPE: str

file

The file.

TYPE: str

line

The 1-based line.

TYPE: int DEFAULT: 0

col

The 0-based column.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
QiecDiagnosticError

The diagnostic, with code qiec-notation.

Source code in src/quivers/dsl/notation/table.py
def fail(
    message: str, *, file: str, line: int = 0, col: int = 0
) -> QiecDiagnosticError:
    """A located notation diagnostic.

    Parameters
    ----------
    message : str
        What was refused.
    file : str
        The file.
    line : int
        The 1-based line.
    col : int
        The 0-based column.

    Returns
    -------
    QiecDiagnosticError
        The diagnostic, with code ``qiec-notation``.
    """
    return QiecDiagnosticError(
        message, code=NOTATION_CODE, file=file, line=line, column=col
    )

is_symbol

is_symbol(text: str) -> bool

Whether a token is a run of symbol characters.

PARAMETER DESCRIPTION
text

The token.

TYPE: str

RETURNS DESCRIPTION
bool

True when no character is a space, an ASCII letter or digit, an underscore, a bracket, a quote, $, or #.

Source code in src/quivers/dsl/notation/table.py
def is_symbol(text: str) -> bool:
    """Whether a token is a run of symbol characters.

    Parameters
    ----------
    text : str
        The token.

    Returns
    -------
    bool
        True when no character is a space, an ASCII letter or digit, an
        underscore, a bracket, a quote, ``$``, or ``#``.
    """
    return bool(text) and all(
        not c.isspace()
        and not (c.isascii() and (c.isalnum() or c == "_"))
        and c not in _SYMBOL_EXCLUDED
        for c in text
    )

is_word

is_word(text: str) -> bool

Whether a token is spelled like a name.

PARAMETER DESCRIPTION
text

The token.

TYPE: str

RETURNS DESCRIPTION
bool

True for [A-Za-z_][A-Za-z0-9_]*.

Source code in src/quivers/dsl/notation/table.py
def is_word(text: str) -> bool:
    """Whether a token is spelled like a name.

    Parameters
    ----------
    text : str
        The token.

    Returns
    -------
    bool
        True for ``[A-Za-z_][A-Za-z0-9_]*``.
    """
    return (
        bool(text)
        and (text[0].isascii() and (text[0].isalpha() or text[0] == "_"))
        and all(c.isascii() and (c.isalnum() or c == "_") for c in text)
    )

piece_edges

piece_edges(item: ShapeItem) -> tuple[bool, bool]

Whether a printed shape item starts and ends like a name.

Two printed pieces are separated by a space exactly when the first ends like a name and the second starts like one, so a name, a literal, or an operand never runs into its neighbour; a symbol token and declared printing space need none.

PARAMETER DESCRIPTION
item

The item.

TYPE: ShapeItem

RETURNS DESCRIPTION
tuple[bool, bool]

Whether its printing starts like a name, and whether it ends like one.

Source code in src/quivers/dsl/notation/table.py
def piece_edges(item: ShapeItem) -> tuple[bool, bool]:
    """Whether a printed shape item starts and ends like a name.

    Two printed pieces are separated by a space exactly when the first ends
    like a name and the second starts like one, so a name, a literal, or
    an operand never runs into its neighbour; a symbol token and declared
    printing space need none.

    Parameters
    ----------
    item : ShapeItem
        The item.

    Returns
    -------
    tuple[bool, bool]
        Whether its printing starts like a name, and whether it ends like
        one.
    """
    if item.role == "space":
        return False, False
    if item.role == "token":
        word = is_word(item.text)
        return word and not item.before, word and not item.after
    return True, True

read_production

read_production(notation: str, production: NotationProduction, syntax: SyntaxInfo, *, file: str, order: int = 0) -> Production

Read one production against its signature.

PARAMETER DESCRIPTION
notation

The flat name of its notation.

TYPE: str

production

The production as written.

TYPE: NotationProduction

syntax

The signature of its notation.

TYPE: SyntaxInfo

file

The file it is written in.

TYPE: str

order

Its declaration order among the active productions.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
Production

The production, each hole with its role and sort.

RAISES DESCRIPTION
QiecDiagnosticError

If the shape has no token and is not juxtaposition, two operand holes are adjacent elsewhere, a token cannot be read, a hole is unused or appears twice in the shape, or the template is not a term of the signature.

Source code in src/quivers/dsl/notation/table.py
def read_production(
    notation: str,
    production: NotationProduction,
    syntax: SyntaxInfo,
    *,
    file: str,
    order: int = 0,
) -> Production:
    """Read one production against its signature.

    Parameters
    ----------
    notation : str
        The flat name of its notation.
    production : NotationProduction
        The production as written.
    syntax : SyntaxInfo
        The signature of its notation.
    file : str
        The file it is written in.
    order : int
        Its declaration order among the active productions.

    Returns
    -------
    Production
        The production, each hole with its role and sort.

    Raises
    ------
    QiecDiagnosticError
        If the shape has no token and is not juxtaposition, two operand
        holes are adjacent elsewhere, a token cannot be read, a hole is
        unused or appears twice in the shape, or the template is not a term
        of the signature.
    """
    holes: dict[str, NotationPatternItem] = {}
    for item in production.items:
        if item.hole is None:
            continue
        if item.hole in holes:
            raise fail(
                f"production `{production.name}` names hole `{item.hole}` twice",
                file=file,
                line=item.line,
                col=item.col,
            )
        holes[item.hole] = item
    reader = _TemplateReader(production, syntax, holes, file)
    template_syntax = production.template
    if template_syntax.kind != "apply" and not (
        template_syntax.kind == "name"
        and template_syntax.name in syntax.signature.constructors
    ):
        raise fail(
            f"production `{production.name}`: the template is a constructor "
            "application of the signature",
            file=file,
            line=production.line,
            col=production.col,
        )
    head = syntax.signature.constructors.get(template_syntax.name)
    if head is None:
        raise fail(
            f"production `{production.name}`: `{template_syntax.name}` is not a "
            f"constructor of {syntax.name}",
            file=file,
            line=template_syntax.line or production.line,
            col=template_syntax.col if template_syntax.line else production.col,
        )
    sort = head.codomain
    template = reader.read(template_syntax, sort, ())
    items: list[ShapeItem] = []
    for item in production.items:
        if item.token is not None:
            before, text, after = _split_spacing(item.token)
            if not text:
                items.append(
                    ShapeItem(
                        role="space", text=item.token, line=item.line, col=item.col
                    )
                )
                continue
            _check_token(text, item, file)
            items.append(
                ShapeItem(
                    role="token",
                    text=text,
                    before=before,
                    after=after,
                    line=item.line,
                    col=item.col,
                )
            )
            continue
        assert item.hole is not None
        assigned = reader.sorts.get(item.hole)
        if assigned is None:
            raise fail(
                f"production `{production.name}`: hole `{item.hole}` is not used "
                "by the template",
                file=file,
                line=item.line,
                col=item.col,
            )
        role, hole_sort = assigned
        items.append(
            ShapeItem(
                role="operand"
                if role == "operand"
                else ("binder" if role == "binder" else "data"),
                text=item.hole,
                sort=hole_sort,
                line=item.line,
                col=item.col,
            )
        )
    built = Production(
        notation=notation,
        name=production.name,
        syntax=syntax.name,
        items=tuple(items),
        template=template,
        sort=sort,
        assoc=_associativity(production.options, file),
        order=order,
        line=production.line,
        col=production.col,
        file=file,
    )
    _check_shape(built)
    return built

syntax_infos

syntax_infos(signatures: Iterable[tuple[str, Signature]]) -> dict[str, SyntaxInfo]

Signatures keyed by flat name, as notation reads them.

PARAMETER DESCRIPTION
signatures

Each signature's flat name and value.

TYPE: Iterable[tuple[str, Signature]]

RETURNS DESCRIPTION
dict[str, SyntaxInfo]

By flat name.

Source code in src/quivers/dsl/notation/table.py
def syntax_infos(signatures: Iterable[tuple[str, Signature]]) -> dict[str, SyntaxInfo]:
    """Signatures keyed by flat name, as notation reads them.

    Parameters
    ----------
    signatures : Iterable[tuple[str, Signature]]
        Each signature's flat name and value.

    Returns
    -------
    dict[str, SyntaxInfo]
        By flat name.
    """
    return {
        name: SyntaxInfo(name=name, signature=signature)
        for name, signature in signatures
    }

read_quotation

read_quotation(items: tuple[NotationItem, ...], table: NotationTable, *, file: str) -> QuotationText

A quotation's context and tokens.

A quotation may begin with a context, the names of the free variables the quoted term may mention, separated by commas and ended by ⊢.

PARAMETER DESCRIPTION
items

The quotation's token tree.

TYPE: tuple[NotationItem, ...]

table

The active notations.

TYPE: NotationTable

file

The file, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
QuotationText

The context names and the term's tokens.

RAISES DESCRIPTION
QiecDiagnosticError

If the context is not names separated by commas, or a token does not read.

Source code in src/quivers/dsl/notation/tokens.py
def read_quotation(
    items: tuple[NotationItem, ...], table: NotationTable, *, file: str
) -> QuotationText:
    """A quotation's context and tokens.

    A quotation may begin with a context, the names of the free variables
    the quoted term may mention, separated by commas and ended by ``⊢``.

    Parameters
    ----------
    items : tuple[NotationItem, ...]
        The quotation's token tree.
    table : NotationTable
        The active notations.
    file : str
        The file, for diagnostics.

    Returns
    -------
    QuotationText
        The context names and the term's tokens.

    Raises
    ------
    QiecDiagnosticError
        If the context is not names separated by commas, or a token does
        not read.
    """
    turnstile = next(
        (
            position
            for position, item in enumerate(items)
            if isinstance(item, NotationAtom)
            and item.category == "symbol"
            and item.text == CONTEXT_TURNSTILE
        ),
        None,
    )
    if turnstile is None:
        return QuotationText(tokens=read_tokens(items, table, file=file))
    context: list[TokenName] = []
    expect_name = True
    for item in items[:turnstile]:
        if (
            expect_name
            and isinstance(item, NotationAtom)
            and item.category == "identifier"
            and "." not in item.text
        ):
            context.append(
                TokenName(
                    text=item.text,
                    start=item.start,
                    end=item.end,
                    line=item.line,
                    col=item.col,
                )
            )
            expect_name = False
            continue
        if (
            not expect_name
            and isinstance(item, NotationAtom)
            and item.category == "symbol"
            and item.text == ","
        ):
            expect_name = True
            continue
        line = getattr(item, "line", 0)
        col = getattr(item, "col", 0)
        raise fail(
            f"a quotation's context is names separated by commas before "
            f"`{CONTEXT_TURNSTILE}`",
            file=file,
            line=line,
            col=col,
        )
    if expect_name and context:
        raise fail(
            f"a quotation's context ends with a name before `{CONTEXT_TURNSTILE}`",
            file=file,
            line=context[-1].line,
            col=context[-1].col,
        )
    names = [name.text for name in context]
    if len(set(names)) != len(names):
        raise fail(
            "a quotation's context names each variable once",
            file=file,
            line=context[0].line,
            col=context[0].col,
        )
    return QuotationText(
        context=tuple(context),
        tokens=read_tokens(items[turnstile + 1 :], table, file=file),
    )

read_tokens

read_tokens(items: tuple[NotationItem, ...], table: NotationTable, *, file: str) -> tuple[ReadToken, ...]

The reader's tokens of a token tree.

PARAMETER DESCRIPTION
items

The token tree.

TYPE: tuple[NotationItem, ...]

table

The active notations.

TYPE: NotationTable

file

The file, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
tuple[ReadToken, ...]

The tokens; parenthesized groups stay groups.

RAISES DESCRIPTION
QiecDiagnosticError

If a symbol run is not made of active tokens, or a square or curly bracket is not an active token.

Source code in src/quivers/dsl/notation/tokens.py
def read_tokens(
    items: tuple[NotationItem, ...], table: NotationTable, *, file: str
) -> tuple[ReadToken, ...]:
    """The reader's tokens of a token tree.

    Parameters
    ----------
    items : tuple[NotationItem, ...]
        The token tree.
    table : NotationTable
        The active notations.
    file : str
        The file, for diagnostics.

    Returns
    -------
    tuple[ReadToken, ...]
        The tokens; parenthesized groups stay groups.

    Raises
    ------
    QiecDiagnosticError
        If a symbol run is not made of active tokens, or a square or curly
        bracket is not an active token.
    """
    tokens: list[ReadToken] = []
    index = 0
    while index < len(items):
        item = items[index]
        if isinstance(item, NotationAtom) and item.category == "symbol":
            run = item.text
            end = item.end
            following = index + 1
            while following < len(items):
                nxt = items[following]
                if (
                    isinstance(nxt, NotationAtom)
                    and nxt.category == "symbol"
                    and nxt.start == end
                ):
                    run += nxt.text
                    end = nxt.end
                    following += 1
                    continue
                break
            tokens.extend(
                _munch(
                    run,
                    table,
                    start=item.start,
                    line=item.line,
                    col=item.col,
                    file=file,
                )
            )
            index = following
            continue
        index += 1
        if isinstance(item, NotationAtom):
            if item.category == "identifier":
                tokens.extend(_split_dotted(item, table))
            elif item.category == "integer":
                tokens.append(
                    TokenLiteral(
                        text=item.text,
                        number=int(item.text),
                        is_text=False,
                        start=item.start,
                        end=item.end,
                        line=item.line,
                        col=item.col,
                    )
                )
            else:
                value = ast.literal_eval(item.text)
                tokens.append(
                    TokenLiteral(
                        text=item.text,
                        string=str(value),
                        is_text=True,
                        start=item.start,
                        end=item.end,
                        line=item.line,
                        col=item.col,
                    )
                )
            continue
        if isinstance(item, NotationAntiquote):
            tokens.append(
                TokenAntiquote(
                    antiquote=item,
                    start=item.start,
                    end=item.end,
                    line=item.line,
                    col=item.col,
                )
            )
            continue
        assert isinstance(item, NotationGroup)
        inner = read_tokens(item.items, table, file=file)
        if item.opener == "(":
            tokens.append(
                TokenGroup(
                    items=inner,
                    start=item.start,
                    end=item.end,
                    line=item.line,
                    col=item.col,
                )
            )
            continue
        closer = "]" if item.opener == "[" else "}"
        for bracket in (item.opener, closer):
            if bracket not in table.tokens:
                raise fail(
                    f"`{bracket}` is not a token of the active notations",
                    file=file,
                    line=item.line,
                    col=item.col,
                )
        tokens.append(
            TokenWord(
                text=item.opener,
                start=item.start,
                end=item.start + 1,
                line=item.line,
                col=item.col,
            )
        )
        tokens.extend(inner)
        tokens.append(
            TokenWord(
                text=closer,
                start=item.end - 1,
                end=item.end,
                line=item.line,
                col=item.col,
            )
        )
    return tuple(tokens)

enforest

Enforestation: reading a quotation's tokens against the active precedence DAG.

The reader follows Danielsson and Norell's grammar for mixfix operators over a precedence graph. A level's expressions are its operators applied to operands of strictly tighter levels, except that a prefix or right-associative operator's last operand may again be of its own level (a right chain) and a postfix or left-associative operator's first operand may be (a left chain). The holes between an operator's tokens take any expression. Closed productions, names, antiquotations, constructor applications Op(a, x. b), and parenthesized groups are atoms, usable anywhere.

The reader is a memoized top-down parser that keeps every reading (up to two per span, which is all ambiguity detection needs), so it reports an ambiguous quotation instead of choosing. When no reading exists, it reads again treating every pair of unrelated levels as nestable; a reading found then shows which two productions lack a precedence relation, and the refusal names both and the notations and modules that declare them.

enforest

enforest(tokens: Sequence[ReadToken], table: NotationTable, sort: SortKey, *, file: str, line: int, col: int) -> Reading

Read a quotation's tokens into exactly one reading.

PARAMETER DESCRIPTION
tokens

The quotation's tokens.

TYPE: Sequence[ReadToken]

table

The active notations.

TYPE: NotationTable

sort

The sort the quotation must build, or None to accept any.

TYPE: SortKey

file

The file, for diagnostics.

TYPE: str

line

The quotation's location.

TYPE: int

col

The quotation's location.

TYPE: int

RETURNS DESCRIPTION
Reading

The reading and its sort.

RAISES DESCRIPTION
QiecDiagnosticError

If the quotation is empty, has no reading, has a reading only when two unrelated productions nest (naming both, their notations, and their modules), or has two readings (naming the productions where they differ).

Source code in src/quivers/dsl/notation/enforest.py
def enforest(
    tokens: Sequence[ReadToken],
    table: NotationTable,
    sort: SortKey,
    *,
    file: str,
    line: int,
    col: int,
) -> Reading:
    """Read a quotation's tokens into exactly one reading.

    Parameters
    ----------
    tokens : Sequence[ReadToken]
        The quotation's tokens.
    table : NotationTable
        The active notations.
    sort : SortKey
        The sort the quotation must build, or ``None`` to accept any.
    file : str
        The file, for diagnostics.
    line, col : int
        The quotation's location.

    Returns
    -------
    Reading
        The reading and its sort.

    Raises
    ------
    QiecDiagnosticError
        If the quotation is empty, has no reading, has a reading only when
        two unrelated productions nest (naming both, their notations, and
        their modules), or has two readings (naming the productions where
        they differ).
    """
    if not tokens:
        raise fail("an empty quotation quotes nothing", file=file, line=line, col=col)
    strict = _Context(table, relaxed=False)
    reader = _Reader(tokens, strict)
    partial = reader.expression(0, sort)
    readings = [
        (node, found_sort) for end, node, found_sort in partial if end == len(tokens)
    ]
    for end, _, _ in partial:
        reader.reach(end)
    if len(readings) > 1:
        first, second = _first_difference(readings[0][0], readings[1][0])
        at = first if isinstance(first, ParseUse) else second
        where_line = getattr(at, "line", line) or line
        where_col = getattr(at, "col", col) if getattr(at, "line", 0) else col
        raise fail(
            f"the quotation reads two ways: as {_head(first, table)} and as "
            f"{_head(second, table)}; parenthesize, or relate the productions",
            file=file,
            line=where_line,
            col=where_col,
        )
    if readings:
        node, found_sort = readings[0]
        syntax, sort_name = found_sort if found_sort is not None else ("", "")
        return Reading(node=node, sort=sort_name, syntax=syntax)
    relaxed = _Reader(tokens, _Context(table, relaxed=True))
    loose = [node for end, node, _ in relaxed.expression(0, sort) if end == len(tokens)]
    for candidate in loose:
        for use, _, operand in _uses(candidate):
            if not isinstance(operand, ParseUse):
                continue
            outer = production_of(use, table)
            inner = production_of(operand, table)
            if outer.fixity == "closed" or inner.fixity == "closed":
                continue
            if table.unrelated(table.level(outer), table.level(inner)):
                raise fail(
                    f"{outer.label} and {inner.label} have no precedence relation, "
                    "so the quotation does not say which applies first; "
                    "parenthesize, or relate them with `>` in a notation",
                    file=file,
                    line=use.line or line,
                    col=use.col if use.line else col,
                )
    failing = reader
    inner_failure = strict.inner_failure
    if inner_failure is not None and reader.furthest < len(tokens):
        stop = reader.token(reader.furthest)
        if isinstance(stop, TokenGroup):
            failing = inner_failure
    stop = failing.token(failing.furthest)
    stop_line = getattr(stop, "line", 0) or line
    stop_col = getattr(stop, "col", 0) if getattr(stop, "line", 0) else col
    raise fail(
        f"the quotation does not read in the active notations at {_describe(stop)}",
        file=file,
        line=stop_line,
        col=stop_col,
    )

notation

Language-server support for notation: hover on quotations, definition of operators.

Hovering a quotation shows the term it elaborates to (its constructor tree, with de Bruijn variables), its sort, and its text printed back through the active notations. Go-to-definition on a token of a quotation reaches the production of the notation that read it, in whichever module declares it.

NotationTarget didactic-model

NotationTarget(*, file: str = '', line: int, col: int, length: int)

Bases: Model

Where a production is declared.

PARAMETER DESCRIPTION
file

Its file, or empty for the document itself.

TYPE: str DEFAULT: ''

line

Its 0-based line in that file.

TYPE: int

col

Its 0-based column.

TYPE: int

length

The length of the production's name.

TYPE: int

quotation_at

quotation_at(module: Module, source: str, line: int, col: int) -> tuple[Quotation, int] | None

The quotation of a document's own module at a position.

PARAMETER DESCRIPTION
module

The program (the document's own statements come first).

TYPE: Module

source

The document's text.

TYPE: str

line

The 0-based line.

TYPE: int

col

The 0-based character column.

TYPE: int

RETURNS DESCRIPTION
tuple[Quotation, int] | None

The innermost quotation covering the position and the position's byte offset, or None.

Source code in src/quivers/lsp/notation.py
def quotation_at(
    module: Module, source: str, line: int, col: int
) -> tuple[Quotation, int] | None:
    """The quotation of a document's own module at a position.

    Parameters
    ----------
    module : Module
        The program (the document's own statements come first).
    source : str
        The document's text.
    line : int
        The 0-based line.
    col : int
        The 0-based character column.

    Returns
    -------
    tuple[Quotation, int] | None
        The innermost quotation covering the position and the position's
        byte offset, or ``None``.
    """
    data = source.encode("utf-8")
    offset = _byte_offset(source, line, col)
    found: list[_Located] = []
    total = source.count("\n") + 1
    for statement in module.statements:
        for quotation in _quotations(statement):
            if not 0 < quotation.line <= total:
                continue
            start = _line_start(data, quotation.line) + quotation.col
            end = start + len(quotation.source.encode("utf-8"))
            if data[start:end].decode("utf-8", errors="replace") != quotation.source:
                continue
            if start <= offset < end:
                found.append(_Located(quotation=quotation, start=start, end=end))
    if not found:
        return None
    best = min(found, key=lambda item: item.end - item.start)
    return best.quotation, offset

notation_hover

notation_hover(module: Module, source: str, line: int, col: int, *, file: str) -> str | None

The hover text of a quotation: the term it elaborates to.

PARAMETER DESCRIPTION
module

The document's program.

TYPE: Module

source

The document's text.

TYPE: str

line

The 0-based line.

TYPE: int

col

The 0-based character column.

TYPE: int

file

The document, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
str | None

Markdown naming the sort, the elaborated constructor tree, and the printed form; the refusal when the quotation does not elaborate; None off a quotation.

Source code in src/quivers/lsp/notation.py
def notation_hover(
    module: Module, source: str, line: int, col: int, *, file: str
) -> str | None:
    """The hover text of a quotation: the term it elaborates to.

    Parameters
    ----------
    module : Module
        The document's program.
    source : str
        The document's text.
    line : int
        The 0-based line.
    col : int
        The 0-based character column.
    file : str
        The document, for diagnostics.

    Returns
    -------
    str | None
        Markdown naming the sort, the elaborated constructor tree, and the
        printed form; the refusal when the quotation does not elaborate;
        ``None`` off a quotation.
    """
    try:
        read = _read(module, source, line, col, file)
    except QiecDiagnosticError as error:
        return f"**Quotation**\n\n{error.message}"
    if read is None:
        return None
    found, program = read
    quoted = found.quoted
    sort = (
        f"{split_module(quoted.syntax)[1]}.{quoted.sort}" if quoted.sort else "spliced"
    )
    lines = [
        f"**Quotation** : `{sort}`",
        "",
        "```qvr",
        render_core(quoted.core),
        "```",
    ]
    if quoted.sort and not _splices(quoted):
        table = program.table(found.active, file=file, line=0, col=0)
        printed = print_term(
            core_term(quoted.core), table, quoted.syntax, quoted.sort, quoted.context
        )
        lines.extend(["", f"Prints as `{printed}`"])
    return "\n".join(lines)

notation_definition

notation_definition(module: Module, source: str, line: int, col: int, *, file: str, source_map: SourceMap | None = None) -> NotationTarget | None

The production that read the token of a quotation at a position.

PARAMETER DESCRIPTION
module

The document's program.

TYPE: Module

source

The document's text.

TYPE: str

line

The 0-based line.

TYPE: int

col

The 0-based character column.

TYPE: int

file

The document.

TYPE: str

source_map

Maps a line of the flat program to its file, when the program is a module graph.

TYPE: SourceMap | None DEFAULT: None

RETURNS DESCRIPTION
NotationTarget | None

The production's name in its declaration, or None when the position is not on a token a production read.

Source code in src/quivers/lsp/notation.py
def notation_definition(
    module: Module,
    source: str,
    line: int,
    col: int,
    *,
    file: str,
    source_map: SourceMap | None = None,
) -> NotationTarget | None:
    """The production that read the token of a quotation at a position.

    Parameters
    ----------
    module : Module
        The document's program.
    source : str
        The document's text.
    line : int
        The 0-based line.
    col : int
        The 0-based character column.
    file : str
        The document.
    source_map : SourceMap | None
        Maps a line of the flat program to its file, when the program is a
        module graph.

    Returns
    -------
    NotationTarget | None
        The production's name in its declaration, or ``None`` when the
        position is not on a token a production read.
    """
    try:
        read = _read(module, source, line, col, file)
    except QiecDiagnosticError:
        return None
    if read is None:
        return None
    found, program = read
    reading = found.quoted.reading
    if reading is None:
        return None
    use = _use_with_token(reading.node, found.offset)
    if use is None:
        return None
    notation, _, name = use.production.rpartition(".")
    declaration = program.notations[notation]
    production = next(p for p in declaration.productions if p.name == name)
    target_file = ""
    target_line = production.line
    if source_map is not None:
        located = source_map.locate(production.line, production.col)
        root = source_map.spans[0] if source_map.spans else None
        if located is not None and root is not None and located.file != root.label:
            target_file = located.file
            target_line = located.line
    return NotationTarget(
        file=target_file, line=target_line - 1, col=production.col, length=len(name)
    )

Module scoping enters through scope_module_notation for a whole module, and through scope_statement and scope_test for one statement or test of a module or functor body, given the notations active where it stands.