Skip to content

Modules

Static interpretation of a module graph: module paths and identities, loaders that find a module's source, name resolution against imported interfaces, the interfaces themselves, and the flat program the compiler sees. The modules reference describes the surface, and the semantics states the resolution rules.

modules

Files as modules: imports, qualified names, visibility, and re-exports.

Each .qvr file is a module whose path follows the directory layout below a search root, so syntax/lambda.qvr is syntax.lambda. A module is a triple of its identity (ModuleIdentity), its public interface (ModuleInterface), and its body. Importing includes another module's interface and keeps the identity of every name it brings in, so a declaration reached along two import paths is one declaration.

Compilation interprets the module graph statically into one flat program (interpret) before any code generation, so the compiler, the reference machine, and every transpile target see a single, fully qualified program.

The entry points are interpret_file, interpret_module, and interpret_source; quivers.dsl.load and quivers.dsl.loads compile their result.

ALLOCATING_EFFECTS module-attribute

ALLOCATING_EFFECTS = frozenset({'Random', 'Param'})

The prelude interfaces whose instances name sites or parameters.

PROGRAM_INSTANCES module-attribute

PROGRAM_INSTANCES: Mapping[str, str] = {'random': 'Random', 'score': 'Score'}

The built-in instances every probabilistic program performs through.

HOLE_MARK module-attribute

HOLE_MARK = '?'

Marks the display of a hole, so ?Worlds never names a source module.

ROOT_MODULE_NAME module-attribute

ROOT_MODULE_NAME = 'main'

The path of a root module given as source text rather than a file.

QUOTED_NAME_POSITIONS module-attribute

QUOTED_NAME_POSITIONS: Mapping[str, int] = {'ValueCall': 0, 'ValueConstruct': 0, 'TypeName': 0, 'TypeApply': 0, 'IndexApply': 0, 'PatternConstructor': 0, 'CompCall': 0, 'MorphClause': 0}

The quoted-syntax constructors whose argument at the given position is a reference to a declaration: a callee, a constructor, a type, an index sort's constructor, or a source constructor of a signature morphism.

MODULE_SUFFIX module-attribute

MODULE_SUFFIX = '.qvr'

The file suffix of a module.

STANDARD_LIBRARY_NAME module-attribute

STANDARD_LIBRARY_NAME = 'std'

The first segment of every module path of the shipped standard library.

STANDARD_LIBRARY_ROOT module-attribute

STANDARD_LIBRARY_ROOT = Path(__file__).resolve().parents[2] / 'stdlib'

The directory the standard library's modules live in, as std/....

MODULE_SUFFIXES module-attribute

MODULE_SUFFIXES = (MODULE_SUFFIX, LITERATE_SUFFIX)

The file suffixes of a module: QVR source and literate Markdown.

ModuleErrorCode

ModuleErrorCode = Literal['module-unknown', 'module-cycle', 'module-ambiguous-path', 'module-alias-clash', 'name-unknown', 'name-private', 'name-ambiguous', 'name-not-imported', 'export-unknown', 'export-clash', 'export-expression', 'open-unknown', 'signature-mismatch', 'signature-item', 'sharing-mismatch', 'module-abstraction', 'module-application', 'module-recursion', 'implicit-ambiguous', 'implicit-missing', 'hole-conflict', 'hole-signature', 'hole-unfilled', 'link-unknown-hole', 'link-conflict', 'link-recursion']

The codes a module diagnostic carries.

Locate

Locate = Callable[[int, int], SourceLocation]

Map a flat-program line and column to the source location they come from.

SiteKind

SiteKind = Literal['sample', 'observe', 'marginal', 'parameter']

What a site is: a program step's draw, observation, or marginalized latent, or a learned parameter.

NameResolver

NameResolver = Callable[[str, int, int], str | None]

Resolve a name written at a line and column of a module to its flat name, or None when the module binds no such name.

ResolutionRole

ResolutionRole = Literal['declaration', 'reference', 'export', 'import']

Why a token resolved: it declares, refers to, exports, or imports a name.

ModuleDiagnostic didactic-model

ModuleDiagnostic(*, code: ModuleErrorCode, message: str, location: SourceLocation, suggestions: tuple[str, ...] = (), related: tuple[SourceLocation, ...] = ())

Bases: Model

One refusal of the module system.

ATTRIBUTE DESCRIPTION
code

The stable code.

TYPE: ModuleErrorCode

message

The description, without the location.

TYPE: str

location

Where the offending token is.

TYPE: SourceLocation

suggestions

Near-miss names, best first.

TYPE: tuple[str, ...]

related

Further locations the message refers to, in order (the imports along a cycle, the two sources of an ambiguous name).

TYPE: tuple[SourceLocation, ...]

render

render() -> str

The diagnostic as one line.

RETURNS DESCRIPTION
str

file:line:col: error[code]: message; did you mean ...?.

Source code in src/quivers/dsl/modules/errors.py
def render(self) -> str:
    """The diagnostic as one line.

    Returns
    -------
    str
        ``file:line:col: error[code]: message; did you mean ...?``.
    """
    text = f"{self.location.render()}: error[{self.code}]: {self.message}"
    if self.suggestions:
        text += (
            "; did you mean "
            + " or ".join(repr(name) for name in self.suggestions)
            + "?"
        )
    return text

ModuleError

ModuleError(diagnostic: ModuleDiagnostic)

Bases: Exception

Raised when the module graph does not load or a name does not resolve.

PARAMETER DESCRIPTION
diagnostic

The structured diagnostic.

TYPE: ModuleDiagnostic

ATTRIBUTE DESCRIPTION
diagnostic

The structured diagnostic.

TYPE: ModuleDiagnostic

Source code in src/quivers/dsl/modules/errors.py
def __init__(self, diagnostic: ModuleDiagnostic) -> None:
    self.diagnostic = diagnostic
    super().__init__(diagnostic.render())

code property

The diagnostic's code.

RETURNS DESCRIPTION
ModuleErrorCode

The stable code.

SourceLocation didactic-model

SourceLocation(*, file: str, line: int = 0, column: int = 0)

Bases: Model

A position in one module's source.

ATTRIBUTE DESCRIPTION
file

The file (or label) of the module's source.

TYPE: str

line

The 1-based line.

TYPE: int

column

The 0-based column.

TYPE: int

render

render() -> str

file:line:column.

RETURNS DESCRIPTION
str

The location as editors and compilers print it.

Source code in src/quivers/dsl/modules/errors.py
def render(self) -> str:
    """``file:line:column``.

    Returns
    -------
    str
        The location as editors and compilers print it.
    """
    return f"{self.file}:{self.line}:{self.column}"

DeductionRequirement didactic-model

DeductionRequirement(*, atom: str, sorts: tuple[str, ...] = (), use: SourceLocation, fixes: tuple[SourceLocation, ...] = ())

Bases: Model

What generic code requires of one open atom of its parameter.

ATTRIBUTE DESCRIPTION
atom

The atom.

TYPE: str

sorts

Per slot, "int", "item", or the name of an open class: a class of the signature (slotN) or one the uses introduce (a, b, ...).

TYPE: tuple[str, ...]

use

The first use, which fixes the arity.

TYPE: SourceLocation

fixes

Per slot, the use that fixes its sort (the first use when no use fixes it).

TYPE: tuple[SourceLocation, ...]

render

render(parameter: str) -> str

The requirement as an interface shows it.

PARAMETER DESCRIPTION
parameter

The parameter's name.

TYPE: str

RETURNS DESCRIPTION
str

requires D.span(a, a, D.Item): Int, the parameter's items, or a class name per slot.

Source code in src/quivers/dsl/modules/generic_uses.py
def render(self, parameter: str) -> str:
    """The requirement as an interface shows it.

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

    Returns
    -------
    str
        ``requires D.span(a, a, D.Item)``: ``Int``, the parameter's
        items, or a class name per slot.
    """
    if not self.sorts:
        return f"requires {parameter}.{self.atom}"
    slots = ", ".join(_render_sort(sort, parameter) for sort in self.sorts)
    return f"requires {parameter}.{self.atom}({slots})"

LoadedModule

LoadedModule(source: ModuleSource, tree: _Tree, names: FileNames)

A module's source, parse tree, and names, before checking.

PARAMETER DESCRIPTION
source

The source.

TYPE: ModuleSource

tree

Its parse tree.

TYPE: _Tree

names

Its name occurrences.

TYPE: FileNames

Source code in src/quivers/dsl/modules/graph.py
def __init__(self, source: ModuleSource, tree: _Tree, names: FileNames) -> None:
    self.source = source
    self.tree = tree
    self.names = names

ModuleGraph

ModuleGraph(root: ModuleIdentity, order: tuple[ModuleIdentity, ...], loaded: Mapping[ModuleIdentity, LoadedModule], checked: Mapping[ModuleIdentity, CheckedModule], holes: Mapping[HoleModule, HoleDeclaration] | None = None, hole_interfaces: Mapping[HoleModule, ModuleInterface] | None = None, links: Mapping[HoleModule, LinkDeclaration] | None = None)

A loaded, acyclic, checked module graph.

PARAMETER DESCRIPTION
root

The module the graph was loaded from.

TYPE: ModuleIdentity

order

Every module, each after the modules it imports; the root is last.

TYPE: tuple[ModuleIdentity, ...]

loaded

Each module's source, tree, and names.

TYPE: Mapping[ModuleIdentity, LoadedModule]

checked

Each module's resolutions and interface.

TYPE: Mapping[ModuleIdentity, CheckedModule]

holes

The package's holes, each with the signature it is checked against.

TYPE: Mapping[HoleModule, HoleDeclaration] DEFAULT: None

hole_interfaces

What a module importing a hole sees: its signature's items.

TYPE: Mapping[HoleModule, ModuleInterface] DEFAULT: None

links

The holes the graph fills, each with its filler.

TYPE: Mapping[HoleModule, LinkDeclaration] DEFAULT: None

Source code in src/quivers/dsl/modules/graph.py
def __init__(
    self,
    root: ModuleIdentity,
    order: tuple[ModuleIdentity, ...],
    loaded: Mapping[ModuleIdentity, LoadedModule],
    checked: Mapping[ModuleIdentity, CheckedModule],
    holes: Mapping[HoleModule, HoleDeclaration] | None = None,
    hole_interfaces: Mapping[HoleModule, ModuleInterface] | None = None,
    links: Mapping[HoleModule, LinkDeclaration] | None = None,
) -> None:
    self.root = root
    self.order = order
    self.loaded = dict(loaded)
    self.checked = dict(checked)
    self.holes = dict(holes or {})
    self.hole_interfaces = dict(hole_interfaces or {})
    self.links = dict(links or {})

interface

interface(identity: ModuleIdentity) -> ModuleInterface

The interface of one module of the graph, or of one of its holes.

PARAMETER DESCRIPTION
identity

The module or hole.

TYPE: ModuleIdentity

RETURNS DESCRIPTION
ModuleInterface

Its public names.

Source code in src/quivers/dsl/modules/graph.py
def interface(self, identity: ModuleIdentity) -> ModuleInterface:
    """The interface of one module of the graph, or of one of its holes.

    Parameters
    ----------
    identity : ModuleIdentity
        The module or hole.

    Returns
    -------
    ModuleInterface
        Its public names.
    """
    if isinstance(identity, HoleModule):
        return self.hole_interfaces[identity]
    return self.checked[identity].interface

imports_of

imports_of(identity: ModuleIdentity) -> tuple[ModuleIdentity, ...]

The modules and holes a module imports directly.

PARAMETER DESCRIPTION
identity

A module of the graph.

TYPE: ModuleIdentity

RETURNS DESCRIPTION
tuple[ModuleIdentity, ...]

Its imports, in order.

Source code in src/quivers/dsl/modules/graph.py
def imports_of(self, identity: ModuleIdentity) -> tuple[ModuleIdentity, ...]:
    """The modules and holes a module imports directly.

    Parameters
    ----------
    identity : ModuleIdentity
        A module of the graph.

    Returns
    -------
    tuple[ModuleIdentity, ...]
        Its imports, in order.
    """
    return tuple(item.module for item in self.checked[identity].imports)

fillings

fillings() -> dict[HoleModule, ModuleIdentity]

The filler of each filled hole.

RETURNS DESCRIPTION
dict[HoleModule, ModuleIdentity]

The fillings.

Source code in src/quivers/dsl/modules/graph.py
def fillings(self) -> dict[HoleModule, ModuleIdentity]:
    """The filler of each filled hole.

    Returns
    -------
    dict[HoleModule, ModuleIdentity]
        The fillings.
    """
    return {hole: link.filler for hole, link in self.links.items()}

hole_closure

hole_closure() -> dict[ModuleIdentity, tuple[HoleModule, ...]]

The holes each module needs (see linking.hole_closure).

RETURNS DESCRIPTION
dict[ModuleIdentity, tuple[HoleModule, ...]]

Each module's holes, sorted by path.

Source code in src/quivers/dsl/modules/graph.py
def hole_closure(self) -> dict[ModuleIdentity, tuple[HoleModule, ...]]:
    """The holes each module needs (see `linking.hole_closure`).

    Returns
    -------
    dict[ModuleIdentity, tuple[HoleModule, ...]]
        Each module's holes, sorted by path.
    """
    return hole_closure(
        self.order,
        {identity: self.imports_of(identity) for identity in self.order},
        self.fillings(),
    )

HoleModule didactic-model

HoleModule(*, path: tuple[str, ...], kind: Literal['hole_module'] = 'hole_module')

Bases: ModuleIdentity

An unfilled hole of a package (hole Worlds : WorldModel).

Modules import a hole by its path like any module and are checked against its signature; linking fills it, and a module that depends on holes is then identified by the fillings it is linked with.

ATTRIBUTE DESCRIPTION
path

The hole's module path's segments.

TYPE: tuple[str, ...]

ModuleIdentity didactic-model

ModuleIdentity()

Bases: TaggedUnion

Which module a module is.

Each variant names one way a module comes to exist. module_display renders any of them for diagnostics and for the module prefix of the flat names its declarations get.

SourceModule didactic-model

SourceModule(*, path: tuple[str, ...], kind: Literal['source_module'] = 'source_module')

Bases: ModuleIdentity

A module given by a source file (or source text).

ATTRIBUTE DESCRIPTION
path

The module path's segments.

TYPE: tuple[str, ...]

AppliedModule didactic-model

AppliedModule(*, functor: ModuleIdentity, arguments: tuple[ModuleArgument, ...] = (), instance: str = '', kind: Literal['applied_module'] = 'applied_module')

Bases: ModuleIdentity

A functor applied to its arguments.

An applicative application is identified by the functor and the arguments alone, so F(X) written twice is one module. A generative one also carries the application it came from, so each application is a module of its own.

ATTRIBUTE DESCRIPTION
functor

The functor or template.

TYPE: ModuleIdentity

arguments

The arguments, in parameter order.

TYPE: tuple[ModuleArgument, ...]

instance

Empty for an applicative application; for a generative one, the application site that makes it distinct.

TYPE: str

ModuleArgument didactic-model

ModuleArgument(*, parameter: str, module: ModuleIdentity)

Bases: Model

One argument of a functor application.

ATTRIBUTE DESCRIPTION
parameter

The parameter it instantiates.

TYPE: str

module

The argument.

TYPE: ModuleIdentity

NestedModule didactic-model

NestedModule(*, parent: ModuleIdentity, name: str, kind: Literal['nested_module'] = 'nested_module')

Bases: ModuleIdentity

A module, signature, or computation template declared inside a module.

ATTRIBUTE DESCRIPTION
parent

The declaring module.

TYPE: ModuleIdentity

name

The declared name.

TYPE: str

ParameterModule didactic-model

ParameterModule(*, functor: ModuleIdentity, name: str, kind: Literal['parameter_module'] = 'parameter_module')

Bases: ModuleIdentity

A functor's (or a template's) module parameter, known by its signature.

Generic code names its parameter's items through this identity; an application substitutes the argument for it, and the generic check gives its abstract items fresh declarations.

ATTRIBUTE DESCRIPTION
functor

The functor or template.

TYPE: ModuleIdentity

name

The parameter's name.

TYPE: str

SealedModule didactic-model

SealedModule(*, module: ModuleIdentity, signature: str, instance: str, kind: Literal['sealed_module'] = 'sealed_module')

Bases: ModuleIdentity

A module sealed by a signature: M :> S.

Sealing hides what the signature leaves abstract, so each sealing is a module of its own, distinct from the sealed module and from every other sealing of it.

ATTRIBUTE DESCRIPTION
module

The sealed module.

TYPE: ModuleIdentity

signature

The signature, as module_display renders its declaring module and name.

TYPE: str

instance

The sealing site.

TYPE: str

InterfaceEntry didactic-model

InterfaceEntry(*, name: str, origin: ModuleIdentity, origin_name: str, kinds: tuple[str, ...] = (), signature: str = '', docs: tuple[str, ...] = (), declared_with: str = '')

Bases: Model

One public name of a module.

ATTRIBUTE DESCRIPTION
name

The name importers use.

TYPE: str

origin

The module that declares it.

TYPE: ModuleIdentity

origin_name

Its name in that module.

TYPE: str

kinds

The declaration kinds of the name (family, computation...).

TYPE: tuple[str, ...]

signature

The declaring source line of each declaration, for documentation.

TYPE: str

docs

The declaration's doc-comment lines, once per declaring statement.

TYPE: tuple[str, ...]

declared_with

The name a declaration that declares several names is known by, when it is not this one: List for its constructor Cons, the syntax Lambda for its constructor App. Empty for the head of a declaration.

TYPE: str

ModuleInterface didactic-model

ModuleInterface(*, identity: ModuleIdentity, entries: tuple[InterfaceEntry, ...] = (), dependencies: tuple[ModuleIdentity, ...] = ())

Bases: Model

What importers of a module see.

ATTRIBUTE DESCRIPTION
identity

The module.

TYPE: ModuleIdentity

entries

The public names, sorted by name.

TYPE: tuple[InterfaceEntry, ...]

dependencies

The modules it imports directly, in import order.

TYPE: tuple[ModuleIdentity, ...]

get

get(name: str) -> InterfaceEntry | None

The entry for a public name.

PARAMETER DESCRIPTION
name

The name.

TYPE: str

RETURNS DESCRIPTION
InterfaceEntry | None

The entry, or None when the name is not public.

Source code in src/quivers/dsl/modules/interface.py
def get(self, name: str) -> InterfaceEntry | None:
    """The entry for a public name.

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

    Returns
    -------
    InterfaceEntry | None
        The entry, or ``None`` when the name is not public.
    """
    for entry in self.entries:
        if entry.name == name:
            return entry
    return None

names

names() -> tuple[str, ...]

The public names.

RETURNS DESCRIPTION
tuple[str, ...]

The names, sorted.

Source code in src/quivers/dsl/modules/interface.py
def names(self) -> tuple[str, ...]:
    """The public names.

    Returns
    -------
    tuple[str, ...]
        The names, sorted.
    """
    return tuple(entry.name for entry in self.entries)

is_reexport

is_reexport(entry: InterfaceEntry) -> bool

Whether an entry is defined by another module.

PARAMETER DESCRIPTION
entry

One of this interface's entries.

TYPE: InterfaceEntry

RETURNS DESCRIPTION
bool

Whether its origin differs from this module.

Source code in src/quivers/dsl/modules/interface.py
def is_reexport(self, entry: InterfaceEntry) -> bool:
    """Whether an entry is defined by another module.

    Parameters
    ----------
    entry : InterfaceEntry
        One of this interface's entries.

    Returns
    -------
    bool
        Whether its origin differs from this module.
    """
    return entry.origin != self.identity

to_artifact

to_artifact() -> bytes

The interface as a canonical JSON document.

RETURNS DESCRIPTION
bytes

UTF-8 JSON with sorted keys and no insignificant whitespace, identical for equal interfaces.

Source code in src/quivers/dsl/modules/interface.py
def to_artifact(self) -> bytes:
    """The interface as a canonical JSON document.

    Returns
    -------
    bytes
        UTF-8 JSON with sorted keys and no insignificant whitespace,
        identical for equal interfaces.
    """
    payload = {
        "module": module_display(self.identity),
        "identity": json.loads(self.identity.model_dump_json()),
        "dependencies": [module_display(item) for item in self.dependencies],
        "entries": [
            {
                "name": entry.name,
                "origin": module_display(entry.origin),
                "origin_name": entry.origin_name,
                "kinds": list(entry.kinds),
                "signature": entry.signature,
                "docs": list(entry.docs),
                "declared_with": entry.declared_with,
            }
            for entry in self.entries
        ],
    }
    return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode(
        "utf-8"
    )

digest

digest() -> str

The SHA-256 digest of to_artifact.

RETURNS DESCRIPTION
str

The hex digest.

Source code in src/quivers/dsl/modules/interface.py
def digest(self) -> str:
    """The SHA-256 digest of `to_artifact`.

    Returns
    -------
    str
        The hex digest.
    """
    return hashlib.sha256(self.to_artifact()).hexdigest()

FlatProgram didactic-model

FlatProgram(*, module: Module, root: ModuleIdentity, source_map: SourceMap, interfaces: tuple[ModuleInterface, ...] = (), checking: Module | None = None, checks: tuple[CheckSite, ...] = (), laws: tuple[LawObligation, ...] = (), unfilled: tuple[HoleModule, ...] = ())

Bases: Model

The module graph interpreted as one program.

ATTRIBUTE DESCRIPTION
module

The flat program: every module's statements, dependencies first, with every name resolved.

TYPE: Module

root

The root module.

TYPE: ModuleIdentity

source_map

Where each flat line comes from.

TYPE: SourceMap

interfaces

Every module's interface, in dependency order.

TYPE: tuple[ModuleInterface, ...]

checking

For a program that uses signatures, functors, sealing, or module parameters, the checking program: the same declarations, except that the abstract items of functor parameters and sealed modules are declarations of their own, generic code is included once at those, and every signature match is witnessed by generated code. It is compiled to check the module layer and discarded.

TYPE: Module | None

checks

The witnesses of the checking program.

TYPE: tuple[CheckSite, ...]

laws

The laws of signatures that matching modules owe, checked once the program is compiled.

TYPE: tuple[LawObligation, ...]

unfilled

The holes the root needs that no link fills. The checking program checks the package with them abstract; the run-time program then holds only the modules that need none of them, and compiling it is refused.

TYPE: tuple[HoleModule, ...]

root_interface property

root_interface: ModuleInterface

The root module's interface.

RETURNS DESCRIPTION
ModuleInterface

What an importer of the root would see.

interface

interface(identity: ModuleIdentity) -> ModuleInterface

One module's interface.

PARAMETER DESCRIPTION
identity

The module.

TYPE: ModuleIdentity

RETURNS DESCRIPTION
ModuleInterface

Its interface.

RAISES DESCRIPTION
KeyError

If the module is not part of the program.

Source code in src/quivers/dsl/modules/interpret.py
def interface(self, identity: ModuleIdentity) -> ModuleInterface:
    """One module's interface.

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

    Returns
    -------
    ModuleInterface
        Its interface.

    Raises
    ------
    KeyError
        If the module is not part of the program.
    """
    for interface in self.interfaces:
        if interface.identity == identity:
            return interface
    raise KeyError(identity)

SourceMap didactic-model

SourceMap(*, spans: tuple[SourceSpan, ...] = ())

Bases: Model

Maps a line of a flat program to its module's file and line.

ATTRIBUTE DESCRIPTION
spans

Each module's lines; the root's start at line 1.

TYPE: tuple[SourceSpan, ...]

locate

locate(line: int, column: int = 0) -> SourceLocation | None

The source location of a flat line.

PARAMETER DESCRIPTION
line

A 1-based line of the flat program.

TYPE: int

column

The column, passed through.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
SourceLocation | None

The file and the line in it, or None for line 0 (no location) or a line outside every module.

Source code in src/quivers/dsl/modules/interpret.py
def locate(self, line: int, column: int = 0) -> SourceLocation | None:
    """The source location of a flat line.

    Parameters
    ----------
    line : int
        A 1-based line of the flat program.
    column : int
        The column, passed through.

    Returns
    -------
    SourceLocation | None
        The file and the line in it, or ``None`` for line 0 (no
        location) or a line outside every module.
    """
    for span in self.spans:
        if span.first_line <= line < span.first_line + span.line_count:
            return SourceLocation(
                file=span.label,
                line=line - span.first_line + 1,
                column=column,
            )
    return None

module_at

module_at(line: int) -> ModuleIdentity | None

The module a flat line belongs to.

PARAMETER DESCRIPTION
line

A 1-based flat line.

TYPE: int

RETURNS DESCRIPTION
ModuleIdentity | None

The module, or None outside every module.

Source code in src/quivers/dsl/modules/interpret.py
def module_at(self, line: int) -> ModuleIdentity | None:
    """The module a flat line belongs to.

    Parameters
    ----------
    line : int
        A 1-based flat line.

    Returns
    -------
    ModuleIdentity | None
        The module, or ``None`` outside every module.
    """
    for span in self.spans:
        if span.first_line <= line < span.first_line + span.line_count:
            return span.module
    return None

SourceSpan didactic-model

SourceSpan(*, module: ModuleIdentity, label: str, first_line: int, line_count: int)

Bases: Model

The lines one module occupies in a flat program.

ATTRIBUTE DESCRIPTION
module

The module.

TYPE: ModuleIdentity

label

Its file (or label).

TYPE: str

first_line

The first flat line of the module.

TYPE: int

line_count

How many lines it has.

TYPE: int

CheckSite didactic-model

CheckSite(*, line: int, message: str, location: SourceLocation)

Bases: Model

Generated code of the checking program that witnesses a match.

ATTRIBUTE DESCRIPTION
line

The witness's line in the checking program (past every source line).

TYPE: int

message

The mismatch the witness reports when it does not check.

TYPE: str

location

Where the match is required.

TYPE: SourceLocation

HoleDeclaration didactic-model

HoleDeclaration(*, hole: HoleModule, module: ModuleIdentity, signature_module: ModuleIdentity, signature_name: str, location: SourceLocation)

Bases: Model

A hole statement of the graph, with its signature resolved.

ATTRIBUTE DESCRIPTION
hole

The hole.

TYPE: HoleModule

module

The module whose hole statement declares it.

TYPE: ModuleIdentity

signature_module

The module that declares the hole's signature.

TYPE: ModuleIdentity

signature_name

The signature's name there.

TYPE: str

location

The hole statement's path token.

TYPE: SourceLocation

LinkDeclaration didactic-model

LinkDeclaration(*, hole: HoleModule, filler: ModuleIdentity, location: SourceLocation)

Bases: Model

One filling of a hole.

ATTRIBUTE DESCRIPTION
hole

The hole filled.

TYPE: HoleModule

filler

The module that fills it.

TYPE: ModuleIdentity

location

Where the link is written (the link statement, or the caller that passed it).

TYPE: SourceLocation

OwnerTie didactic-model

OwnerTie(*, owner: str, target: str)

Bases: Model

One declaration's learned parameters tied to another's.

ATTRIBUTE DESCRIPTION
owner

The tied flat declaration.

TYPE: str

target

The declaration whose parameters they are.

TYPE: str

ShareError

ShareError(message: str, statement: ShareDecl)

Bases: SiteError

A share that does not tie two compatible sites or owners.

PARAMETER DESCRIPTION
message

What does not match, naming both sides.

TYPE: str

statement

The share statement.

TYPE: ShareDecl

Source code in src/quivers/dsl/modules/sites.py
def __init__(self, message: str, statement: ShareDecl) -> None:
    super().__init__(f"line {statement.line}, col {statement.col}: {message}")
    self.statement = statement

SiteAddress didactic-model

SiteAddress(*, module: str, declaration: str, label: str)

Bases: Model

Where a site is, as people read it.

ATTRIBUTE DESCRIPTION
module

The declaring module, extended by its instantiation.

TYPE: str

declaration

The declaring declaration's name in that module.

TYPE: str

label

The site's label below the declaration (prior, theta$z for the site z of a program drawn under theta, lex.0 for a parameter).

TYPE: str

render

render() -> str

The address as one dotted path.

RETURNS DESCRIPTION
str

module.declaration.label.

Source code in src/quivers/dsl/modules/sites.py
def render(self) -> str:
    """The address as one dotted path.

    Returns
    -------
    str
        ``module.declaration.label``.
    """
    return MEMBER_SEPARATOR.join((self.module, self.declaration, self.label))

SiteError

Bases: ValueError

A site address, pattern, or stored record that does not resolve.

The message names the address, pattern, or record that does not resolve.

SitePattern didactic-model

SitePattern(*, text: str, segments: tuple[str, ...])

Bases: Model

A path pattern over site addresses.

A pattern is an address with wildcards. Within a segment, * matches any run of characters, so Discourse(*) matches every instantiation of Discourse; a whole segment ** matches any number of segments. A pattern is matched against the end of an address, so fit.prior selects the site prior of every declaration fit and Discourse(*).fit.prior that site in every instance of Discourse wherever it is declared.

ATTRIBUTE DESCRIPTION
text

The pattern as written.

TYPE: str

segments

Its segments.

TYPE: tuple[str, ...]

parse classmethod

parse(text: str) -> SitePattern

Read a pattern.

PARAMETER DESCRIPTION
text

The pattern.

TYPE: str

RETURNS DESCRIPTION
SitePattern

The pattern.

RAISES DESCRIPTION
SiteError

If it is empty, has an empty segment, or does not balance.

Source code in src/quivers/dsl/modules/sites.py
@classmethod
def parse(cls, text: str) -> SitePattern:
    """Read a pattern.

    Parameters
    ----------
    text : str
        The pattern.

    Returns
    -------
    SitePattern
        The pattern.

    Raises
    ------
    SiteError
        If it is empty, has an empty segment, or does not balance.
    """
    segments = address_segments(text)
    if not text or any(not segment for segment in segments):
        raise SiteError(f"site pattern {text!r} has an empty segment")
    return cls(text=text, segments=segments)

matches

matches(address: SiteAddress) -> bool

Whether the pattern selects an address.

PARAMETER DESCRIPTION
address

The address.

TYPE: SiteAddress

RETURNS DESCRIPTION
bool

Whether some suffix of the address's segments matches.

Source code in src/quivers/dsl/modules/sites.py
def matches(self, address: SiteAddress) -> bool:
    """Whether the pattern selects an address.

    Parameters
    ----------
    address : SiteAddress
        The address.

    Returns
    -------
    bool
        Whether some suffix of the address's segments matches.
    """
    target = address_segments(address.render())
    compiled = [_segment_regex(segment) for segment in self.segments]
    return any(_match(compiled, target[start:]) for start in range(len(target) + 1))

SiteRecord didactic-model

SiteRecord(*, address: SiteAddress, kind: SiteKind, identity: str, key: str, target: str)

Bases: Model

One site or parameter of an entry point.

ATTRIBUTE DESCRIPTION
address

Where it is.

TYPE: SiteAddress

kind

What it is.

TYPE: SiteKind

identity

Its rename-stable identity.

TYPE: str

key

What a run reads it under: the label a run conditions a sample site on, or the spelled name a Param store holds a parameter under.

TYPE: str

target

What a transpiled program calls it.

TYPE: str

SiteTable didactic-model

SiteTable(*, entry: str, sites: tuple[SiteRecord, ...] = ())

Bases: Model

The sites and parameters of one entry point.

ATTRIBUTE DESCRIPTION
entry

The entry point's flat-program name.

TYPE: str

sites

Its sample sites, in the program's step order, then the learned parameters its computations read, by key.

TYPE: tuple[SiteRecord, ...]

record

record(key: str) -> SiteRecord

The site a run reads under a key.

PARAMETER DESCRIPTION
key

A sample site's label or a parameter's name.

TYPE: str

RETURNS DESCRIPTION
SiteRecord

The site.

RAISES DESCRIPTION
SiteError

If no site of the entry has the key.

Source code in src/quivers/dsl/modules/sites.py
def record(self, key: str) -> SiteRecord:
    """The site a run reads under a key.

    Parameters
    ----------
    key : str
        A sample site's label or a parameter's name.

    Returns
    -------
    SiteRecord
        The site.

    Raises
    ------
    SiteError
        If no site of the entry has the key.
    """
    for site in self.sites:
        if site.key == key:
            return site
    raise SiteError(f"entry {self.entry!r} has no site {key!r}")

select

select(pattern: str) -> tuple[SiteRecord, ...]

The sites a path pattern selects.

PARAMETER DESCRIPTION
pattern

A pattern (see SitePattern).

TYPE: str

RETURNS DESCRIPTION
tuple[SiteRecord, ...]

The sites whose address the pattern matches, in table order.

Source code in src/quivers/dsl/modules/sites.py
def select(self, pattern: str) -> tuple[SiteRecord, ...]:
    """The sites a path pattern selects.

    Parameters
    ----------
    pattern : str
        A pattern (see `SitePattern`).

    Returns
    -------
    tuple[SiteRecord, ...]
        The sites whose address the pattern matches, in table order.
    """
    compiled = SitePattern.parse(pattern)
    return tuple(site for site in self.sites if compiled.matches(site.address))

resolve

resolve(bindings: Mapping[str, V], *, allow_runtime_labels: bool = False) -> dict[str, V]

Key values by the run's site keys, reading patterns as addresses.

A key that is a site's own key binds that site; any other key is a path pattern and binds every site it selects.

PARAMETER DESCRIPTION
bindings

Values by site key or path pattern.

TYPE: Mapping[str, V]

allow_runtime_labels

Pass through an unlisted bare label or a label with an occurrence number. The runtime checks that it reaches the requested draw.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
dict[str, V]

The values by site key.

RAISES DESCRIPTION
SiteError

If a pattern selects no site, or two bindings give one site.

Source code in src/quivers/dsl/modules/sites.py
def resolve[V](
    self, bindings: Mapping[str, V], *, allow_runtime_labels: bool = False
) -> dict[str, V]:
    """Key values by the run's site keys, reading patterns as addresses.

    A key that is a site's own key binds that site; any other key is a
    path pattern and binds every site it selects.

    Parameters
    ----------
    bindings : Mapping[str, V]
        Values by site key or path pattern.
    allow_runtime_labels : bool
        Pass through an unlisted bare label or a label with an occurrence
        number. The runtime checks that it reaches the requested draw.

    Returns
    -------
    dict[str, V]
        The values by site key.

    Raises
    ------
    SiteError
        If a pattern selects no site, or two bindings give one site.
    """
    keys = {site.key for site in self.sites}
    resolved: dict[str, V] = {}
    origin: dict[str, str] = {}
    for written, value in bindings.items():
        selected = (
            (written,)
            if written in keys
            else tuple(site.key for site in self.select(written))
        )
        if not selected and allow_runtime_labels:
            label, marker, occurrence = written.rpartition("@")
            if written.isidentifier() or (
                marker and label.isidentifier() and occurrence.isdecimal()
            ):
                selected = (written,)
        if not selected:
            raise SiteError(
                f"{written!r} names no site of entry {self.entry!r}; its sites "
                "are " + ", ".join(site.address.render() for site in self.sites)
            )
        for key in selected:
            if key in resolved:
                raise SiteError(
                    f"site {key!r} is bound by both {origin[key]!r} and {written!r}"
                )
            resolved[key] = value
            origin[key] = written
    return resolved

reverse_map

reverse_map() -> dict[str, str]

Each target spelling mapped to the address it spells.

RETURNS DESCRIPTION
dict[str, str]

The rendered address of each site, by its target spelling.

Source code in src/quivers/dsl/modules/sites.py
def reverse_map(self) -> dict[str, str]:
    """Each target spelling mapped to the address it spells.

    Returns
    -------
    dict[str, str]
        The rendered address of each site, by its target spelling.
    """
    return {site.target: site.address.render() for site in self.sites}

readdress

readdress(stored: SiteTable) -> dict[str, str]

Map a stored table's keys onto this table's, by identity.

PARAMETER DESCRIPTION
stored

The table a run record was stored with, possibly under other spellings.

TYPE: SiteTable

RETURNS DESCRIPTION
dict[str, str]

Each stored key mapped to the key the same site has now.

RAISES DESCRIPTION
SiteError

If a stored site's identity names no site of this entry: the declaration that declared it changed, so the stored values no longer describe it.

Source code in src/quivers/dsl/modules/sites.py
def readdress(self, stored: SiteTable) -> dict[str, str]:
    """Map a stored table's keys onto this table's, by identity.

    Parameters
    ----------
    stored : SiteTable
        The table a run record was stored with, possibly under other
        spellings.

    Returns
    -------
    dict[str, str]
        Each stored key mapped to the key the same site has now.

    Raises
    ------
    SiteError
        If a stored site's identity names no site of this entry: the
        declaration that declared it changed, so the stored values no
        longer describe it.
    """
    current = {site.identity: site.key for site in self.sites}
    mapped: dict[str, str] = {}
    for site in stored.sites:
        key = current.get(site.identity)
        if key is None:
            raise SiteError(
                f"stored site {site.address.render()} has no counterpart in "
                f"entry {self.entry!r}: its declaration changed"
            )
        mapped[site.key] = key
    return mapped

to_data

to_data() -> dict[str, object]

The table as JSON-compatible data, the reverse map of a run record.

RETURNS DESCRIPTION
dict[str, object]

The entry and, per site, its rendered address, its parts, kind, identity, key, and target spelling.

Source code in src/quivers/dsl/modules/sites.py
def to_data(self) -> dict[str, object]:
    """The table as JSON-compatible data, the reverse map of a run record.

    Returns
    -------
    dict[str, object]
        The entry and, per site, its rendered address, its parts, kind,
        identity, key, and target spelling.
    """
    return {
        "entry": self.entry,
        "sites": [
            {
                "address": site.address.render(),
                "module": site.address.module,
                "declaration": site.address.declaration,
                "label": site.address.label,
                "kind": site.kind,
                "identity": site.identity,
                "key": site.key,
                "target": site.target,
            }
            for site in self.sites
        ],
    }

from_data classmethod

from_data(data: Mapping[str, object]) -> SiteTable

Read a table back from to_data's form.

PARAMETER DESCRIPTION
data

The stored form.

TYPE: Mapping[str, object]

RETURNS DESCRIPTION
SiteTable

The table.

RAISES DESCRIPTION
SiteError

If the form is malformed.

Source code in src/quivers/dsl/modules/sites.py
@classmethod
def from_data(cls, data: Mapping[str, object]) -> SiteTable:
    """Read a table back from `to_data`'s form.

    Parameters
    ----------
    data : Mapping[str, object]
        The stored form.

    Returns
    -------
    SiteTable
        The table.

    Raises
    ------
    SiteError
        If the form is malformed.
    """
    entry = data.get("entry")
    sites = data.get("sites")
    if not isinstance(entry, str) or not isinstance(sites, list):
        raise SiteError("a stored site table needs an entry and a site list")
    records: list[SiteRecord] = []
    for item in sites:
        if not isinstance(item, Mapping):
            raise SiteError("a stored site is a mapping")
        fields = {
            name: item.get(name)
            for name in (
                "module",
                "declaration",
                "label",
                "kind",
                "identity",
                "key",
                "target",
            )
        }
        if not all(isinstance(value, str) for value in fields.values()):
            raise SiteError(f"stored site {item!r} lacks a field")
        kind = fields["kind"]
        if kind not in ("sample", "observe", "marginal", "parameter"):
            raise SiteError(f"stored site kind {kind!r} is not a site kind")
        records.append(
            SiteRecord(
                address=SiteAddress(
                    module=str(fields["module"]),
                    declaration=str(fields["declaration"]),
                    label=str(fields["label"]),
                ),
                kind=kind,
                identity=str(fields["identity"]),
                key=str(fields["key"]),
                target=str(fields["target"]),
            )
        )
    return cls(entry=entry, sites=tuple(records))

SiteTie didactic-model

SiteTie(*, declaration: str, label: str, target_declaration: str, target_label: str)

Bases: Model

One sample site tied to another: they are one site.

ATTRIBUTE DESCRIPTION
declaration, label

The tied site: its flat declaration and its label.

TYPE: str

target_declaration, target_label

The site it is.

TYPE: str

SiteTies didactic-model

SiteTies(*, sites: tuple[SiteTie, ...] = (), owners: tuple[OwnerTie, ...] = ())

Bases: Model

Declared sharing: sites and parameter owners tied to another's.

ATTRIBUTE DESCRIPTION
sites

The tied sample sites.

TYPE: tuple[SiteTie, ...]

owners

The tied parameter owners.

TYPE: tuple[OwnerTie, ...]

site

site(declaration: str, label: str) -> tuple[str, str]

The site a site is tied to, following ties to their end.

PARAMETER DESCRIPTION
declaration

The declaring flat declaration.

TYPE: str

label

The site's label.

TYPE: str

RETURNS DESCRIPTION
tuple[str, str]

The declaration and label of the site it is, itself when untied.

Source code in src/quivers/dsl/modules/sites.py
def site(self, declaration: str, label: str) -> tuple[str, str]:
    """The site a site is tied to, following ties to their end.

    Parameters
    ----------
    declaration : str
        The declaring flat declaration.
    label : str
        The site's label.

    Returns
    -------
    tuple[str, str]
        The declaration and label of the site it is, itself when untied.
    """
    current = (declaration, label)
    seen = {current}
    table = {
        (tie.declaration, tie.label): (tie.target_declaration, tie.target_label)
        for tie in self.sites
    }
    while current in table:
        current = table[current]
        if current in seen:
            break
        seen.add(current)
    return current

owner

owner(owner: str) -> str

The declaration whose parameters an owner's are, following ties.

PARAMETER DESCRIPTION
owner

A flat declaration with learned parameters.

TYPE: str

RETURNS DESCRIPTION
str

The owner it shares with, itself when untied.

Source code in src/quivers/dsl/modules/sites.py
def owner(self, owner: str) -> str:
    """The declaration whose parameters an owner's are, following ties.

    Parameters
    ----------
    owner : str
        A flat declaration with learned parameters.

    Returns
    -------
    str
        The owner it shares with, itself when untied.
    """
    table = {tie.owner: tie.target for tie in self.owners}
    current = owner
    seen = {current}
    while current in table:
        current = table[current]
        if current in seen:
            break
        seen.add(current)
    return current

NameParameter didactic-model

NameParameter(*, parameters: tuple[str, ...] = (), names: tuple[int, ...] = ())

Bases: Model

How a computation receives quoted names through its value parameters.

PARAMETER DESCRIPTION
parameters

The names of its value parameters, in order, so a named argument finds its position.

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

names

The positions of the parameters that carry a quoted name: those whose value reaches a quoted-name position, directly or through another computation's name parameter.

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

NameParameters didactic-model

NameParameters(*, computations: dict[str, NameParameter] = {}, local_computations: dict[str, dict[str, NameParameter]] = {})

Bases: Model

The name parameters of the computations a program has declared so far.

A string is a quoted name when it reaches a quoted-name position, so a computation whose parameter flows into one, as image does in define binary(image : String) = return ValueCall(image, ...), receives a quoted name there, and a literal written as that argument is resolved where it is written, as a literal written at the position itself is. This infers which strings are names from how they are used, the way a type system with a separate type of names would check them.

PARAMETER DESCRIPTION
computations

Each module-level computation, under the name the flat program gives it.

TYPE: dict[str, NameParameter] DEFAULT: {}

local_computations

Each module-level computation's where definitions, by name.

TYPE: dict[str, dict[str, NameParameter]] DEFAULT: {}

learn

learn(statements: Sequence[Statement]) -> NameParameters

Add the computations one module declares.

Modules are learned in dependency order, so every computation a module calls from another module is already known; the module's own computations, which may call each other in any order, are solved together as a least fixed point.

PARAMETER DESCRIPTION
statements

The module's statements, with names as the flat program spells them.

TYPE: Sequence[Statement]

RETURNS DESCRIPTION
NameParameters

The table with the module's computations added.

Source code in src/quivers/dsl/modules/quoted_names.py
def learn(self, statements: Sequence[Statement]) -> NameParameters:
    """Add the computations one module declares.

    Modules are learned in dependency order, so every computation a
    module calls from another module is already known; the module's
    own computations, which may call each other in any order, are
    solved together as a least fixed point.

    Parameters
    ----------
    statements : Sequence[Statement]
        The module's statements, with names as the flat program spells
        them.

    Returns
    -------
    NameParameters
        The table with the module's computations added.
    """
    declared: list[QiecComputationDecl] = []
    for statement in statements:
        item = (
            statement.declaration if isinstance(statement, MetaDecl) else statement
        )
        if isinstance(item, QiecComputationDecl):
            declared.append(item)
    computations = dict(self.computations)
    local_computations = dict(self.local_computations)
    for decl in declared:
        computations[decl.name] = _unknown(decl)
        local_computations[decl.name] = {
            local.name: _unknown(local) for local in decl.locals
        }
    changed = True
    while changed:
        changed = False
        for decl in declared:
            locals_ = local_computations[decl.name]
            for local in decl.locals:
                found = _carried(local, computations, locals_)
                if found != locals_[local.name].names:
                    locals_ = {
                        **locals_,
                        local.name: locals_[local.name].with_(names=found),
                    }
                    local_computations[decl.name] = locals_
                    changed = True
            found = _carried(decl, computations, locals_)
            if found != computations[decl.name].names:
                computations[decl.name] = computations[decl.name].with_(names=found)
                changed = True
    return self.with_(
        computations=computations, local_computations=local_computations
    )

ChainLoader

ChainLoader(loaders: Iterable[ModuleLoader])

Consult several loaders, the first that has a module winning.

PARAMETER DESCRIPTION
loaders

The loaders, in priority order.

TYPE: Iterable[ModuleLoader]

Source code in src/quivers/dsl/modules/loader.py
def __init__(self, loaders: Iterable[ModuleLoader]) -> None:
    self.loaders = tuple(loaders)

find

find(path: tuple[str, ...]) -> tuple[ModuleSource, ...]

The sources of the first loader that has the module.

PARAMETER DESCRIPTION
path

The module path's segments.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
tuple[ModuleSource, ...]

That loader's sources, or nothing.

Source code in src/quivers/dsl/modules/loader.py
def find(self, path: tuple[str, ...]) -> tuple[ModuleSource, ...]:
    """The sources of the first loader that has the module.

    Parameters
    ----------
    path : tuple[str, ...]
        The module path's segments.

    Returns
    -------
    tuple[ModuleSource, ...]
        That loader's sources, or nothing.
    """
    for loader in self.loaders:
        found = loader.find(path)
        if found:
            return found
    return ()

available

available() -> tuple[str, ...]

Every path any loader can find.

RETURNS DESCRIPTION
tuple[str, ...]

The dotted paths, sorted.

Source code in src/quivers/dsl/modules/loader.py
def available(self) -> tuple[str, ...]:
    """Every path any loader can find.

    Returns
    -------
    tuple[str, ...]
        The dotted paths, sorted.
    """
    return tuple(
        sorted({path for loader in self.loaders for path in loader.available()})
    )

FileSystemLoader

FileSystemLoader(roots: Iterable[str | Path])

Find modules as .qvr and .qvr.md files below search roots.

PARAMETER DESCRIPTION
roots

The directories module paths are relative to.

TYPE: Iterable[str | Path]

Source code in src/quivers/dsl/modules/loader.py
def __init__(self, roots: Iterable[str | Path]) -> None:
    self.roots = tuple(Path(root).resolve() for root in roots)

find

find(path: tuple[str, ...]) -> tuple[ModuleSource, ...]

Every root's file for a module path.

PARAMETER DESCRIPTION
path

The module path's segments.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
tuple[ModuleSource, ...]

One source per file <root>/<path>.qvr or <root>/<path>.qvr.md; a root with both provides the module twice, which loading refuses as ambiguous.

Source code in src/quivers/dsl/modules/loader.py
def find(self, path: tuple[str, ...]) -> tuple[ModuleSource, ...]:
    """Every root's file for a module path.

    Parameters
    ----------
    path : tuple[str, ...]
        The module path's segments.

    Returns
    -------
    tuple[ModuleSource, ...]
        One source per file ``<root>/<path>.qvr`` or
        ``<root>/<path>.qvr.md``; a root with both provides the module
        twice, which loading refuses as ambiguous.
    """
    found: list[ModuleSource] = []
    for root in self.roots:
        for suffix in MODULE_SUFFIXES:
            candidate = root.joinpath(*path[:-1], path[-1] + suffix)
            if candidate.is_file():
                found.append(
                    ModuleSource(
                        identity=SourceModule(path=path),
                        label=str(candidate),
                        text=read_module_text(candidate),
                        file=str(candidate),
                    )
                )
    return tuple(found)

available

available() -> tuple[str, ...]

Every module below the roots.

RETURNS DESCRIPTION
tuple[str, ...]

The dotted paths of every .qvr and .qvr.md file whose relative path is a module path.

Source code in src/quivers/dsl/modules/loader.py
def available(self) -> tuple[str, ...]:
    """Every module below the roots.

    Returns
    -------
    tuple[str, ...]
        The dotted paths of every ``.qvr`` and ``.qvr.md`` file whose
        relative path is a module path.
    """
    paths: set[str] = set()
    for root in self.roots:
        for suffix in MODULE_SUFFIXES:
            for file in root.rglob("*" + suffix):
                dotted = ".".join(_relative_module_parts(file.relative_to(root)))
                try:
                    parse_module_path(dotted)
                except ValueError:
                    continue
                paths.add(dotted)
    return tuple(sorted(paths))

module_path_of

module_path_of(file: str | Path) -> tuple[str, ...]

The module path of a file below one of the roots.

PARAMETER DESCRIPTION
file

A .qvr file.

TYPE: str | Path

RETURNS DESCRIPTION
tuple[str, ...]

Its module path.

RAISES DESCRIPTION
ValueError

If the file lies below no root, or its relative path is not a module path.

Source code in src/quivers/dsl/modules/loader.py
def module_path_of(self, file: str | Path) -> tuple[str, ...]:
    """The module path of a file below one of the roots.

    Parameters
    ----------
    file : str | Path
        A ``.qvr`` file.

    Returns
    -------
    tuple[str, ...]
        Its module path.

    Raises
    ------
    ValueError
        If the file lies below no root, or its relative path is not a
        module path.
    """
    resolved = Path(file).resolve()
    for root in self.roots:
        if resolved.is_relative_to(root):
            relative = resolved.relative_to(root)
            return parse_module_path(".".join(_relative_module_parts(relative)))
    raise ValueError(
        f"{file} lies below none of the module roots "
        + ", ".join(str(root) for root in self.roots)
    )

root_path_of

root_path_of(file: str | Path) -> tuple[str, ...]

The path of a file compiled as a root module.

A root is named by its location like any module, but it is never found by an import, so its file name need not be an identifier: lexical-uncertainty.qvr is a root module named lexical-uncertainty, which no module can import.

PARAMETER DESCRIPTION
file

A .qvr file.

TYPE: str | Path

RETURNS DESCRIPTION
tuple[str, ...]

Its path segments relative to the root containing it.

RAISES DESCRIPTION
ValueError

If the file lies below no root.

Source code in src/quivers/dsl/modules/loader.py
def root_path_of(self, file: str | Path) -> tuple[str, ...]:
    """The path of a file compiled as a root module.

    A root is named by its location like any module, but it is never
    found by an import, so its file name need not be an identifier:
    ``lexical-uncertainty.qvr`` is a root module named
    ``lexical-uncertainty``, which no module can import.

    Parameters
    ----------
    file : str | Path
        A ``.qvr`` file.

    Returns
    -------
    tuple[str, ...]
        Its path segments relative to the root containing it.

    Raises
    ------
    ValueError
        If the file lies below no root.
    """
    resolved = Path(file).resolve()
    for root in self.roots:
        if resolved.is_relative_to(root):
            return _relative_module_parts(resolved.relative_to(root))
    raise ValueError(
        f"{file} lies below none of the module roots "
        + ", ".join(str(root) for root in self.roots)
    )

MappingLoader

MappingLoader(modules: Mapping[str, str], *, label: str = '<module>')

Hold module sources in memory, keyed by dotted module path.

PARAMETER DESCRIPTION
modules

Each dotted module path mapped to its source text.

TYPE: Mapping[str, str]

label

The prefix of the label each module's diagnostics name.

TYPE: str DEFAULT: '<module>'

Source code in src/quivers/dsl/modules/loader.py
def __init__(self, modules: Mapping[str, str], *, label: str = "<module>") -> None:
    self.modules = {parse_module_path(path): text for path, text in modules.items()}
    self.label = label

find

find(path: tuple[str, ...]) -> tuple[ModuleSource, ...]

The held source of a module path.

PARAMETER DESCRIPTION
path

The module path's segments.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
tuple[ModuleSource, ...]

The source, or nothing when the path is not held.

Source code in src/quivers/dsl/modules/loader.py
def find(self, path: tuple[str, ...]) -> tuple[ModuleSource, ...]:
    """The held source of a module path.

    Parameters
    ----------
    path : tuple[str, ...]
        The module path's segments.

    Returns
    -------
    tuple[ModuleSource, ...]
        The source, or nothing when the path is not held.
    """
    text = self.modules.get(path)
    if text is None:
        return ()
    dotted = ".".join(path)
    return (
        ModuleSource(
            identity=SourceModule(path=path),
            label=f"{self.label} {dotted}",
            text=text,
        ),
    )

available

available() -> tuple[str, ...]

Every held module path.

RETURNS DESCRIPTION
tuple[str, ...]

The dotted paths, sorted.

Source code in src/quivers/dsl/modules/loader.py
def available(self) -> tuple[str, ...]:
    """Every held module path.

    Returns
    -------
    tuple[str, ...]
        The dotted paths, sorted.
    """
    return tuple(sorted(".".join(path) for path in self.modules))

ModuleLoader

Bases: Protocol

Answers which sources a module path names.

find

find(path: tuple[str, ...]) -> tuple[ModuleSource, ...]

Every source named by a module path.

PARAMETER DESCRIPTION
path

The module path's segments.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
tuple[ModuleSource, ...]

The sources, one per root that has the module (empty when none does).

Source code in src/quivers/dsl/modules/loader.py
def find(self, path: tuple[str, ...]) -> tuple[ModuleSource, ...]:
    """Every source named by a module path.

    Parameters
    ----------
    path : tuple[str, ...]
        The module path's segments.

    Returns
    -------
    tuple[ModuleSource, ...]
        The sources, one per root that has the module (empty when none
        does).
    """
    ...

available

available() -> tuple[str, ...]

Every module path this loader can find, dotted.

RETURNS DESCRIPTION
tuple[str, ...]

The paths, sorted.

Source code in src/quivers/dsl/modules/loader.py
def available(self) -> tuple[str, ...]:
    """Every module path this loader can find, dotted.

    Returns
    -------
    tuple[str, ...]
        The paths, sorted.
    """
    ...

ModuleSource didactic-model

ModuleSource(*, identity: SourceModule, label: str, text: str, file: str | None = None)

Bases: Model

The source of one module.

ATTRIBUTE DESCRIPTION
identity

The module's identity.

TYPE: SourceModule

label

The file path (or label) diagnostics name.

TYPE: str

text

The source text.

TYPE: str

file

The absolute file path, when the source is a file.

TYPE: str | None

StandardLibraryLoader

StandardLibraryLoader(root: Path = STANDARD_LIBRARY_ROOT)

Find the modules of the standard library that ships with quivers.

It answers exactly the paths whose first segment is std, from the package's own directory, so a module path std.semiring names the shipped module wherever the program is loaded from.

PARAMETER DESCRIPTION
root

The directory holding std/; the shipped one by default.

TYPE: Path DEFAULT: STANDARD_LIBRARY_ROOT

Source code in src/quivers/dsl/modules/loader.py
def __init__(self, root: Path = STANDARD_LIBRARY_ROOT) -> None:
    self.files = FileSystemLoader((root,))

find

find(path: tuple[str, ...]) -> tuple[ModuleSource, ...]

The shipped source of a standard library module path.

PARAMETER DESCRIPTION
path

The module path's segments.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
tuple[ModuleSource, ...]

The module's source, or nothing for a path outside std.

Source code in src/quivers/dsl/modules/loader.py
def find(self, path: tuple[str, ...]) -> tuple[ModuleSource, ...]:
    """The shipped source of a standard library module path.

    Parameters
    ----------
    path : tuple[str, ...]
        The module path's segments.

    Returns
    -------
    tuple[ModuleSource, ...]
        The module's source, or nothing for a path outside ``std``.
    """
    if not path or path[0] != STANDARD_LIBRARY_NAME:
        return ()
    return self.files.find(path)

available

available() -> tuple[str, ...]

Every module of the standard library.

RETURNS DESCRIPTION
tuple[str, ...]

The dotted paths below std, sorted.

Source code in src/quivers/dsl/modules/loader.py
def available(self) -> tuple[str, ...]:
    """Every module of the standard library.

    Returns
    -------
    tuple[str, ...]
        The dotted paths below ``std``, sorted.
    """
    return tuple(
        path
        for path in self.files.available()
        if path.split(".")[0] == STANDARD_LIBRARY_NAME
    )

CheckedModule didactic-model

CheckedModule(*, source: ModuleSource, names: FileNames, resolutions: tuple[Resolution, ...] = (), imports: tuple[ResolvedImport, ...] = (), interface: ModuleInterface, region: str = '', module_identity: ModuleIdentity | None = None)

Bases: Model

A module resolved against its dependencies' interfaces.

ATTRIBUTE DESCRIPTION
source

The module's source.

TYPE: ModuleSource

names

Its name occurrences.

TYPE: FileNames

resolutions

Every token that named a module-level name or split into member accesses, in source order.

TYPE: tuple[Resolution, ...]

imports

Its imports.

TYPE: tuple[ResolvedImport, ...]

interface

What its importers see.

TYPE: ModuleInterface

region

The region node of a module declared inside a file, "" for the file's own module.

TYPE: str

module_identity

The identity of a module declared inside a file (its source's identity is the file's).

TYPE: ModuleIdentity | None

identity property

identity: ModuleIdentity

The module's identity.

RETURNS DESCRIPTION
ModuleIdentity

The identity of the module, the source's for a file.

Resolution didactic-model

Resolution(*, start: int, end: int, role: ResolutionRole = 'reference', symbol: Symbol | None = None, module: ModuleIdentity | None = None, path: tuple[str, ...] = (), members: int = 0, name_start: int = 0, name_end: int = 0, line: int = 0, column: int = 0)

Bases: Model

What one name token resolved to.

ATTRIBUTE DESCRIPTION
start, end

The token's byte span.

TYPE: int

role

Why the token names the symbol.

TYPE: ResolutionRole

symbol

The module-level name, or None for a local value whose only resolution is the split into its member accesses.

TYPE: Symbol | None

path

The member path of a declaration the symbol generates, as in the Item of G.Item.

TYPE: tuple[str, ...]

members

Trailing segments that select members of the referenced value.

TYPE: int

name_start, name_end

The byte span of the segment that spells the symbol's own name, the span a rename rewrites.

TYPE: int

line, column

The token's location.

TYPE: int

module

For a token in a module or value position that names a whole module (an import, an alias, a module parameter), that module; symbol is then None.

TYPE: ModuleIdentity | None

ResolvedImport didactic-model

ResolvedImport(*, record: ModuleImport, module: ModuleIdentity)

Bases: Model

One import statement and the module it names.

ATTRIBUTE DESCRIPTION
record

The statement.

TYPE: ModuleImport

module

The imported module.

TYPE: ModuleIdentity

Symbol didactic-model

Symbol(*, module: ModuleIdentity, name: str, kinds: tuple[str, ...] = ())

Bases: Model

A module-level name, identified by where it is declared.

ATTRIBUTE DESCRIPTION
module

The declaring module.

TYPE: ModuleIdentity

name

The name in that module.

TYPE: str

kinds

Its declaration kinds.

TYPE: tuple[str, ...]

module_error

module_error(code: ModuleErrorCode, message: str, location: SourceLocation, *, suggestions: tuple[str, ...] = (), related: tuple[SourceLocation, ...] = ()) -> ModuleError

Build a ModuleError.

PARAMETER DESCRIPTION
code

The stable code.

TYPE: ModuleErrorCode

message

The description.

TYPE: str

location

The offending token's location.

TYPE: SourceLocation

suggestions

Near-miss names.

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

related

Further locations.

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

RETURNS DESCRIPTION
ModuleError

The error, ready to raise.

Source code in src/quivers/dsl/modules/errors.py
def module_error(
    code: ModuleErrorCode,
    message: str,
    location: SourceLocation,
    *,
    suggestions: tuple[str, ...] = (),
    related: tuple[SourceLocation, ...] = (),
) -> ModuleError:
    """Build a `ModuleError`.

    Parameters
    ----------
    code : ModuleErrorCode
        The stable code.
    message : str
        The description.
    location : SourceLocation
        The offending token's location.
    suggestions : tuple[str, ...]
        Near-miss names.
    related : tuple[SourceLocation, ...]
        Further locations.

    Returns
    -------
    ModuleError
        The error, ready to raise.
    """
    return ModuleError(
        ModuleDiagnostic(
            code=code,
            message=message,
            location=location,
            suggestions=suggestions,
            related=related,
        )
    )

near_misses

near_misses(name: str, candidates: Iterable[str], *, limit: int = 3) -> tuple[str, ...]

The candidates closest to a misspelled name.

PARAMETER DESCRIPTION
name

The name as written.

TYPE: str

candidates

The names that would have resolved.

TYPE: Iterable[str]

limit

The most suggestions to return.

TYPE: int DEFAULT: 3

RETURNS DESCRIPTION
tuple[str, ...]

Close candidates, best first.

Source code in src/quivers/dsl/modules/errors.py
def near_misses(
    name: str, candidates: Iterable[str], *, limit: int = 3
) -> tuple[str, ...]:
    """The candidates closest to a misspelled name.

    Parameters
    ----------
    name : str
        The name as written.
    candidates : Iterable[str]
        The names that would have resolved.
    limit : int
        The most suggestions to return.

    Returns
    -------
    tuple[str, ...]
        Close candidates, best first.
    """
    return tuple(get_close_matches(name, sorted(set(candidates)), n=limit, cutoff=0.6))

allocation

allocation(statement: Statement, effect_of: Callable[[str], str]) -> str | None

What a declaration allocates, if anything.

PARAMETER DESCRIPTION
statement

A walked declaration.

TYPE: Statement

effect_of

The interface name of an effect instance, by the instance's name in the flat program.

TYPE: Callable[[str], str]

RETURNS DESCRIPTION
str | None

A description of what it allocates, or None when it allocates nothing.

Source code in src/quivers/dsl/modules/generativity.py
def allocation(statement: Statement, effect_of: Callable[[str], str]) -> str | None:
    """What a declaration allocates, if anything.

    Parameters
    ----------
    statement : Statement
        A walked declaration.
    effect_of : Callable[[str], str]
        The interface name of an effect instance, by the instance's name in
        the flat program.

    Returns
    -------
    str | None
        A description of what it allocates, or ``None`` when it allocates
        nothing.
    """
    if isinstance(statement, QiecComputationDecl):
        for entry in statement.effects.entries:
            effect = effect_of(entry.instance)
            if effect in ALLOCATING_EFFECTS:
                return (
                    f"computation {statement.name} performs {entry.instance} : {effect}"
                )
        return None
    if isinstance(statement, ProgramDecl):
        return f"program {statement.name} names sample sites"
    if isinstance(statement, MorphismDecl):
        role = _morphism_role(statement)
        if role in _NON_ALLOCATING_ROLES:
            return None
        return (
            f"morphism {', '.join(statement.names)} ({role}) owns learnable parameters"
        )
    if isinstance(statement, DeductionDecl):
        learnable_rules = [
            rule.name
            for rule in statement.rules
            if any(option.key in ("learnable", "weight") for option in rule.options)
        ]
        latent = [
            entry
            for entry in statement.lexicon
            if not isinstance(entry.category, LexiconCategoryFixed)
        ]
        if (
            learnable_rules
            or latent
            or any(option.key == "learnable" for option in statement.options)
        ):
            return f"deduction {statement.name} owns learnable weights"
        return None
    if isinstance(statement, EncoderDecl | DecoderDecl):
        return f"{statement.kind.removesuffix('_decl')} {statement.name} owns learnable parameters"
    return None

infer_requirements

infer_requirements(declarations: Iterable[Model], parameters: Mapping[ParameterModule, Mapping[str, tuple[str, ...] | None]], locate: Locate) -> dict[ParameterModule, dict[str, DeductionRequirement]]

What generic code requires of the open atoms of its deduction parameters.

PARAMETER DESCRIPTION
declarations

The checking program's declarations.

TYPE: Iterable[Model]

parameters

Each Deduction extends S parameter, with its constructors: the slot sorts S fixes (quivers.dsl.deduction_reification.slot_classes), or None for an atom S's rules never mention.

TYPE: Mapping[ParameterModule, Mapping[str, tuple[str, ...] | None]]

locate

Where a flat-program line and column come from.

TYPE: Locate

RETURNS DESCRIPTION
dict[ParameterModule, dict[str, DeductionRequirement]]

Per parameter, the requirement on each open atom its generic code names, by atom.

RAISES DESCRIPTION
ModuleError

With code module-abstraction, at the second use, when generic code applies one open atom to two numbers of arguments, or uses one slot as an Int and as an item.

Source code in src/quivers/dsl/modules/generic_uses.py
def infer_requirements(
    declarations: Iterable[dx.Model],
    parameters: Mapping[ParameterModule, Mapping[str, tuple[str, ...] | None]],
    locate: Locate,
) -> dict[ParameterModule, dict[str, DeductionRequirement]]:
    """What generic code requires of the open atoms of its deduction parameters.

    Parameters
    ----------
    declarations : Iterable[dx.Model]
        The checking program's declarations.
    parameters : Mapping[ParameterModule, Mapping[str, tuple[str, ...] | None]]
        Each ``Deduction extends S`` parameter, with its constructors: the
        slot sorts ``S`` fixes (`quivers.dsl.deduction_reification.slot_classes`),
        or ``None`` for an atom ``S``'s rules never mention.
    locate : Locate
        Where a flat-program line and column come from.

    Returns
    -------
    dict[ParameterModule, dict[str, DeductionRequirement]]
        Per parameter, the requirement on each open atom its generic code
        names, by atom.

    Raises
    ------
    ModuleError
        With code ``module-abstraction``, at the second use, when generic
        code applies one open atom to two numbers of arguments, or uses
        one slot as an ``Int`` and as an item.
    """
    scan = _Scan(
        tuple(
            _Parameter(parameter, symbols) for parameter, symbols in parameters.items()
        ),
        locate,
    )
    for declaration in declarations:
        scan.declaration(declaration)
    return scan.requirements()

render_slots

render_slots(sorts: tuple[str, ...]) -> str

Slot sorts as a diagnostic shows them.

PARAMETER DESCRIPTION
sorts

"int", "item", or a class name per slot.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
str

The sorts, parenthesized and comma-separated.

Source code in src/quivers/dsl/modules/generic_uses.py
def render_slots(sorts: tuple[str, ...]) -> str:
    """Slot sorts as a diagnostic shows them.

    Parameters
    ----------
    sorts : tuple[str, ...]
        ``"int"``, ``"item"``, or a class name per slot.

    Returns
    -------
    str
        The sorts, parenthesized and comma-separated.
    """
    return f"({', '.join(sorts)})"

load_graph

load_graph(root: ModuleSource, loader: ModuleLoader, *, links: Mapping[str, str] | None = None) -> ModuleGraph

Load every module root reaches and check each in dependency order.

A module path some module declares a hole is a hole: importing it imports the hole's signature, and no file is loaded for it. A link (in a module, or in links) fills a hole with a module, which is loaded and checked with the graph.

PARAMETER DESCRIPTION
root

The root module's source.

TYPE: ModuleSource

loader

Finds imported modules.

TYPE: ModuleLoader

links

Further fillings, hole path to module path, as a package manifest or an experiment gives them.

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

RETURNS DESCRIPTION
ModuleGraph

The loaded and checked graph.

RAISES DESCRIPTION
ModuleError

If an import names no module or a module two roots both provide, the imports form a cycle, a module fails to resolve, a hole or link is malformed (a signature that is not found, a hole declared with two signatures, a link to a path that is not a hole, a hole linked twice), or the links are not well founded.

ParseError

If a module does not parse.

Source code in src/quivers/dsl/modules/graph.py
def load_graph(
    root: ModuleSource,
    loader: ModuleLoader,
    *,
    links: Mapping[str, str] | None = None,
) -> ModuleGraph:
    """Load every module ``root`` reaches and check each in dependency order.

    A module path some module declares a ``hole`` is a hole: importing it
    imports the hole's signature, and no file is loaded for it. A ``link``
    (in a module, or in ``links``) fills a hole with a module, which is
    loaded and checked with the graph.

    Parameters
    ----------
    root : ModuleSource
        The root module's source.
    loader : ModuleLoader
        Finds imported modules.
    links : Mapping[str, str] | None
        Further fillings, hole path to module path, as a package manifest
        or an experiment gives them.

    Returns
    -------
    ModuleGraph
        The loaded and checked graph.

    Raises
    ------
    quivers.dsl.modules.errors.ModuleError
        If an import names no module or a module two roots both provide,
        the imports form a cycle, a module fails to resolve, a hole or
        link is malformed (a signature that is not found, a hole declared
        with two signatures, a link to a path that is not a hole, a hole
        linked twice), or the links are not well founded.
    quivers.dsl.parser.ParseError
        If a module does not parse.
    """
    extra_links = dict(links or {})
    cache: dict[ModuleIdentity, LoadedModule] = {root.identity: _load_one(root)}
    extra_paths = tuple(parse_module_path(text) for text in extra_links.values())
    hole_paths: frozenset[tuple[str, ...]] = frozenset()
    while True:
        reached = _reachable(root.identity, cache, loader, hole_paths, extra_paths)
        found_paths = frozenset(
            parse_module_path(record.path)
            for identity in reached
            for record in cache[identity].names.holes
        )
        if found_paths <= hole_paths:
            break
        hole_paths = hole_paths | found_paths
    holes, hole_interfaces = _holes(reached, cache)
    declared_links, fillers_of = _links(reached, cache, holes, extra_links)
    fillers_of.setdefault(root.identity, []).extend(
        SourceModule(path=path) for path in extra_paths
    )
    loaded: dict[ModuleIdentity, LoadedModule] = {root.identity: cache[root.identity]}
    order: list[ModuleIdentity] = []
    finished: set[ModuleIdentity] = set()
    edges: dict[ModuleIdentity, tuple[ResolvedImport, ...]] = {}

    def require(
        target: SourceModule,
        text: str,
        location: SourceLocation,
        path_so_far: tuple[tuple[ModuleIdentity, SourceLocation | None], ...],
    ) -> None:
        on_path = [item for item, _ in path_so_far]
        if target in on_path:
            start = on_path.index(target)
            cycle = [*on_path[start:], target]
            related = tuple(
                item_location
                for _, item_location in path_so_far[start + 1 :]
                if item_location is not None
            )
            raise module_error(
                "module-cycle",
                "import cycle: "
                + " -> ".join(module_display(item) for item in cycle)
                + "; the module graph must be acyclic",
                location,
                related=(*related, location),
            )
        if target not in loaded:
            cached = cache.get(target)
            loaded[target] = (
                cached
                if cached is not None
                else _load_one(_found(loader, target.path, text, location))
            )
        if target not in finished:
            visit(target, location, path_so_far)

    def visit(
        identity: ModuleIdentity,
        reached_by: SourceLocation | None,
        stack: tuple[tuple[ModuleIdentity, SourceLocation | None], ...],
    ) -> None:
        module = loaded[identity]
        path_so_far = (*stack, (identity, reached_by))
        on_path = [item for item, _ in path_so_far]
        resolved: list[ResolvedImport] = []
        for record in module.names.imports:
            location = _location(module.source, record.line, record.column)
            try:
                path = parse_module_path(record.path)
            except ValueError as error:
                raise module_error("module-unknown", str(error), location) from error
            if path in hole_paths:
                hole = HoleModule(path=path)
                resolved.append(ResolvedImport(record=record, module=hole))
                declaring = holes[hole].module
                if declaring not in on_path and declaring not in finished:
                    assert isinstance(declaring, SourceModule)
                    require(declaring, record.path, location, path_so_far)
                continue
            target = SourceModule(path=path)
            require(target, record.path, location, path_so_far)
            resolved.append(ResolvedImport(record=record, module=target))
        for filler in fillers_of.get(identity, ()):
            link_location = _location(module.source, 0, 0)
            for hole, link in declared_links.items():
                if link.filler == filler:
                    link_location = link.location
            if filler not in on_path:
                require(filler, module_display(filler), link_location, path_so_far)
        edges[identity] = tuple(resolved)
        finished.add(identity)
        order.append(identity)

    visit(root.identity, None, ())
    checked: dict[ModuleIdentity, CheckedModule] = {}

    def interface_of(target: ModuleIdentity) -> ModuleInterface:
        if isinstance(target, HoleModule):
            return hole_interfaces[target]
        return checked[target].interface

    for identity in order:
        module = loaded[identity]
        interfaces = {
            item.module: interface_of(item.module) for item in edges[identity]
        }
        private = {
            item.module: (
                frozenset()
                if isinstance(item.module, HoleModule)
                else frozenset(
                    declared.name for declared in loaded[item.module].names.declarations
                )
                - frozenset(checked[item.module].interface.names())
            )
            for item in edges[identity]
        }
        constructors = visible_constructors(module.names, edges[identity], interfaces)
        if constructors:
            module.names = file_names(
                module.tree,
                module.source.label,
                constructors=constructors
                | frozenset(
                    item.name
                    for item in module.names.declarations
                    if item.kind == "constructor"
                ),
            )
        checked[identity] = check_module(
            module.source,
            module.names,
            edges[identity],
            interfaces,
            private,
        )
    if declared_links:
        check_well_founded(
            order,
            checked,
            declared_links,
            {
                link.filler: checked[link.filler].interface
                for link in declared_links.values()
            },
        )
    return ModuleGraph(
        root.identity,
        tuple(order),
        loaded,
        checked,
        holes=holes,
        hole_interfaces=hole_interfaces,
        links=declared_links,
    )

visible_constructors

visible_constructors(names: FileNames, imports: tuple[ResolvedImport, ...], interfaces: Mapping[ModuleIdentity, ModuleInterface]) -> frozenset[str]

Imported constructors a bare pattern name may refer to.

PARAMETER DESCRIPTION
names

The importing module's names.

TYPE: FileNames

imports

Its imports.

TYPE: tuple[ResolvedImport, ...]

interfaces

The interfaces of the modules it imports.

TYPE: Mapping[ModuleIdentity, ModuleInterface]

RETURNS DESCRIPTION
frozenset[str]

The constructor names that a selection list, an exclusion, or an open brings into unqualified scope.

Source code in src/quivers/dsl/modules/graph.py
def visible_constructors(
    names: FileNames,
    imports: tuple[ResolvedImport, ...],
    interfaces: Mapping[ModuleIdentity, ModuleInterface],
) -> frozenset[str]:
    """Imported constructors a bare pattern name may refer to.

    Parameters
    ----------
    names : FileNames
        The importing module's names.
    imports : tuple[ResolvedImport, ...]
        Its imports.
    interfaces : Mapping[ModuleIdentity, ModuleInterface]
        The interfaces of the modules it imports.

    Returns
    -------
    frozenset[str]
        The constructor names that a selection list, an exclusion, or an
        ``open`` brings into unqualified scope.
    """
    found: set[str] = set()
    opened = {record.module for record in names.opens}
    for resolved in imports:
        record = resolved.record
        unqualified = (
            record.items is not None
            or bool(record.hidden)
            or (record.alias or record.path) in opened
        )
        if not unqualified:
            continue
        for entry in interfaces[resolved.module].entries:
            if "constructor" in entry.kinds:
                found.add(entry.name)
    return frozenset(found)

flat_name

flat_name(identity: ModuleIdentity, name: str) -> str

The flat-program name of one of a module's declarations.

PARAMETER DESCRIPTION
identity

The declaring module.

TYPE: ModuleIdentity

name

The declaration's name in the module, possibly a generated member such as G.Item.

TYPE: str

RETURNS DESCRIPTION
str

display:name.

Source code in src/quivers/dsl/modules/identity.py
def flat_name(identity: ModuleIdentity, name: str) -> str:
    """The flat-program name of one of a module's declarations.

    Parameters
    ----------
    identity : ModuleIdentity
        The declaring module.
    name : str
        The declaration's name in the module, possibly a generated member
        such as ``G.Item``.

    Returns
    -------
    str
        ``display:name``.
    """
    return module_qualified(module_display(identity), name)

module_display

module_display(identity: ModuleIdentity) -> str

A module identity as people read it.

A nested module extends its parent's display with its name, an application is F(A,B) (with #site when generative), a functor's parameter is F#W, and a sealing is (M:>S)#site; the rendering is injective.

PARAMETER DESCRIPTION
identity

The identity.

TYPE: ModuleIdentity

RETURNS DESCRIPTION
str

The dotted module path for a source module; ? and the path for a hole.

RAISES DESCRIPTION
TypeError

If identity is a variant this function does not render.

Source code in src/quivers/dsl/modules/identity.py
def module_display(identity: ModuleIdentity) -> str:
    """A module identity as people read it.

    A nested module extends its parent's display with its name, an
    application is ``F(A,B)`` (with ``#site`` when generative), a
    functor's parameter is ``F#W``, and a sealing is ``(M:>S)#site``; the
    rendering is injective.

    Parameters
    ----------
    identity : ModuleIdentity
        The identity.

    Returns
    -------
    str
        The dotted module path for a source module; ``?`` and the path for
        a hole.

    Raises
    ------
    TypeError
        If ``identity`` is a variant this function does not render.
    """
    if isinstance(identity, SourceModule):
        return ".".join(identity.path)
    if isinstance(identity, HoleModule):
        return HOLE_MARK + ".".join(identity.path)
    if isinstance(identity, NestedModule):
        return f"{module_display(identity.parent)}.{identity.name}"
    if isinstance(identity, ParameterModule):
        return f"{module_display(identity.functor)}#{identity.name}"
    if isinstance(identity, AppliedModule):
        arguments = ",".join(module_display(item.module) for item in identity.arguments)
        rendered = f"{module_display(identity.functor)}({arguments})"
        return f"{rendered}#{identity.instance}" if identity.instance else rendered
    if isinstance(identity, SealedModule):
        return (
            f"({module_display(identity.module)}:>{identity.signature})"
            f"#{identity.instance}"
        )
    raise TypeError(f"no display for module identity {type(identity).__name__}")

parse_module_path

parse_module_path(text: str) -> tuple[str, ...]

Split a dotted module path into its segments.

PARAMETER DESCRIPTION
text

A dotted path such as syntax.lambda.

TYPE: str

RETURNS DESCRIPTION
tuple[str, ...]

The segments.

RAISES DESCRIPTION
ValueError

If a segment is not an identifier.

Source code in src/quivers/dsl/modules/identity.py
def parse_module_path(text: str) -> tuple[str, ...]:
    """Split a dotted module path into its segments.

    Parameters
    ----------
    text : str
        A dotted path such as ``syntax.lambda``.

    Returns
    -------
    tuple[str, ...]
        The segments.

    Raises
    ------
    ValueError
        If a segment is not an identifier.
    """
    segments = tuple(text.split("."))
    for segment in segments:
        if not _SEGMENT.fullmatch(segment):
            raise ValueError(f"{text!r} is not a module path")
    return segments

source_module

source_module(text: str) -> SourceModule

The identity of the source module with a dotted path.

PARAMETER DESCRIPTION
text

The dotted path.

TYPE: str

RETURNS DESCRIPTION
SourceModule

Its identity.

RAISES DESCRIPTION
ValueError

If text is not a module path.

Source code in src/quivers/dsl/modules/identity.py
def source_module(text: str) -> SourceModule:
    """The identity of the source module with a dotted path.

    Parameters
    ----------
    text : str
        The dotted path.

    Returns
    -------
    SourceModule
        Its identity.

    Raises
    ------
    ValueError
        If ``text`` is not a module path.
    """
    return SourceModule(path=parse_module_path(text))

meta_only_modules

meta_only_modules(graph: ModuleGraph) -> frozenset[ModuleIdentity]

The modules of a graph that serve its meta phase only.

A module serves the meta phase alone when the root reaches it, and every path from the root to it crosses a meta import. An import of a hole reaches the hole's filler. A module the root does not reach at all, such as the filler of a hole no module imports, is not meta code: the link that brings it into the program is run-time code, so it is checked against its hole's signature as run-time code, like every other filler.

PARAMETER DESCRIPTION
graph

The loaded graph.

TYPE: ModuleGraph

RETURNS DESCRIPTION
frozenset[ModuleIdentity]

The modules reached, but only through meta imports.

Source code in src/quivers/dsl/modules/interpret.py
def meta_only_modules(graph: ModuleGraph) -> frozenset[ModuleIdentity]:
    """The modules of a graph that serve its meta phase only.

    A module serves the meta phase alone when the root reaches it, and
    every path from the root to it crosses a ``meta import``. An import of a
    hole reaches the hole's filler. A module the root does not reach at
    all, such as the filler of a hole no module imports, is not meta code:
    the ``link`` that brings it into the program is run-time code, so it is
    checked against its hole's signature as run-time code, like every other
    filler.

    Parameters
    ----------
    graph : ModuleGraph
        The loaded graph.

    Returns
    -------
    frozenset[ModuleIdentity]
        The modules reached, but only through meta imports.
    """
    run_time = _reached(graph, through_meta=False)
    reached = _reached(graph, through_meta=True)
    return frozenset(
        identity
        for identity in graph.order
        if identity in reached and identity not in run_time
    )

name_view

name_view(checked: CheckedModule, root: ModuleIdentity, line_offset: int) -> NameView

The view one module's walk reads its names through.

PARAMETER DESCRIPTION
checked

The resolved module.

TYPE: CheckedModule

root

The program's root.

TYPE: ModuleIdentity

line_offset

Added to the module's lines.

TYPE: int

RETURNS DESCRIPTION
NameView

Each resolved token's flat reference and member split.

Source code in src/quivers/dsl/modules/interpret.py
def name_view(
    checked: CheckedModule, root: ModuleIdentity, line_offset: int
) -> NameView:
    """The view one module's walk reads its names through.

    Parameters
    ----------
    checked : CheckedModule
        The resolved module.
    root : ModuleIdentity
        The program's root.
    line_offset : int
        Added to the module's lines.

    Returns
    -------
    NameView
        Each resolved token's flat reference and member split.
    """
    uses: list[NameUse] = []
    for resolution in checked.resolutions:
        if resolution.role == "import":
            continue
        if resolution.symbol is None:
            original = checked.source.text.encode("utf-8")[
                resolution.start : resolution.end
            ].decode("utf-8")
            segments = original.split(".")
            uses.append(
                NameUse(
                    start=resolution.start,
                    end=resolution.end,
                    reference=".".join(segments[: len(segments) - resolution.members]),
                    members=resolution.members,
                )
            )
            continue
        reference = symbol_flat_name(resolution.symbol, root)
        if resolution.path:
            reference = member_name(reference, *resolution.path)
        uses.append(
            NameUse(
                start=resolution.start,
                end=resolution.end,
                reference=reference,
                members=resolution.members,
            )
        )
    return NameView(uses=tuple(uses), line_offset=line_offset)

symbol_flat_name

symbol_flat_name(symbol: Symbol, root: ModuleIdentity) -> str

The flat-program name of a module-level name.

PARAMETER DESCRIPTION
symbol

The name and its declaring module.

TYPE: Symbol

root

The root of the program.

TYPE: ModuleIdentity

RETURNS DESCRIPTION
str

The bare name for a root declaration; module:name otherwise.

Source code in src/quivers/dsl/modules/interpret.py
def symbol_flat_name(symbol: Symbol, root: ModuleIdentity) -> str:
    """The flat-program name of a module-level name.

    Parameters
    ----------
    symbol : Symbol
        The name and its declaring module.
    root : ModuleIdentity
        The root of the program.

    Returns
    -------
    str
        The bare name for a root declaration; ``module:name`` otherwise.
    """
    if symbol.module == root:
        return symbol.name
    return flat_name(symbol.module, symbol.name)

check_well_founded

check_well_founded(order: Iterable[ModuleIdentity], checked: Mapping[ModuleIdentity, CheckedModule], links: Mapping[HoleModule, LinkDeclaration], filler_interface: Mapping[ModuleIdentity, ModuleInterface]) -> None

Refuse a linked program in which a declaration depends on itself through declarations of other modules.

Imports alone never form a cycle (the module graph is acyclic), but a filling can: worlds.boolean may use the hole Lexicon that lex.core fills, while lex.core uses the hole Worlds that worlds.boolean fills. Such mutually recursive linking is well founded when the declarations themselves are: every declaration of the linked program is defined from declarations that are defined before it, across modules. A declaration that reaches itself through another module's declaration has no such definition, and the link is refused with the cycle's path.

PARAMETER DESCRIPTION
order

The graph's modules.

TYPE: Iterable[ModuleIdentity]

checked

Each module's resolutions.

TYPE: Mapping[ModuleIdentity, CheckedModule]

links

The fillings.

TYPE: Mapping[HoleModule, LinkDeclaration]

filler_interface

Each filler's interface, which tells which declaration a hole's item is in the filler.

TYPE: Mapping[ModuleIdentity, ModuleInterface]

RAISES DESCRIPTION
ModuleError

With code link-recursion and the path of the cycle.

Source code in src/quivers/dsl/modules/linking.py
def check_well_founded(
    order: Iterable[ModuleIdentity],
    checked: Mapping[ModuleIdentity, CheckedModule],
    links: Mapping[HoleModule, LinkDeclaration],
    filler_interface: Mapping[ModuleIdentity, ModuleInterface],
) -> None:
    """Refuse a linked program in which a declaration depends on itself
    through declarations of other modules.

    Imports alone never form a cycle (the module graph is acyclic), but a
    filling can: ``worlds.boolean`` may use the hole ``Lexicon`` that
    ``lex.core`` fills, while ``lex.core`` uses the hole ``Worlds`` that
    ``worlds.boolean`` fills. Such mutually recursive linking is well
    founded when the declarations themselves are: every declaration of the
    linked program is defined from declarations that are defined before
    it, across modules. A declaration that reaches itself through another
    module's declaration has no such definition, and the link is refused
    with the cycle's path.

    Parameters
    ----------
    order : Iterable[ModuleIdentity]
        The graph's modules.
    checked : Mapping[ModuleIdentity, CheckedModule]
        Each module's resolutions.
    links : Mapping[HoleModule, LinkDeclaration]
        The fillings.
    filler_interface : Mapping[ModuleIdentity, ModuleInterface]
        Each filler's interface, which tells which declaration a hole's
        item is in the filler.

    Raises
    ------
    ModuleError
        With code ``link-recursion`` and the path of the cycle.
    """
    edges: dict[_DeclarationNode, list[tuple[_DeclarationNode, HoleModule | None]]] = {}
    for module in order:
        result = checked[module]
        statements: dict[int, list[str]] = {}
        for declared in result.names.declarations:
            statements.setdefault(declared.statement, []).append(declared.name)
        starts = {item.start: item.statement for item in result.names.occurrences}
        for resolution in result.resolutions:
            symbol = resolution.symbol
            if resolution.role != "reference" or symbol is None:
                continue
            statement = starts.get(resolution.start)
            if statement is None:
                continue
            through: HoleModule | None = None
            target_module = symbol.module
            target_name = symbol.name
            if isinstance(target_module, HoleModule):
                link = links.get(target_module)
                if link is None:
                    continue
                through = target_module
                entry = filler_interface[link.filler].get(symbol.name)
                if entry is None:
                    continue
                target_module, target_name = entry.origin, entry.origin_name
            elif not isinstance(target_module, SourceModule):
                continue
            target = _DeclarationNode(module=target_module, name=target_name)
            for name in statements.get(statement, ()):
                source = _DeclarationNode(module=module, name=name)
                if source != target:
                    edges.setdefault(source, []).append((target, through))
    for start in sorted(edges, key=lambda node: node.render()):
        cycle = _cycle_through(start, edges)
        if cycle is None:
            continue
        modules = {node.module for node, _ in cycle}
        if len(modules) < 2:
            continue
        holes = [hole for _, hole in cycle if hole is not None]
        location = links[holes[0]].location if holes else SourceLocation(file="<links>")
        raise module_error(
            "link-recursion",
            "the link is not well founded: "
            + " -> ".join(node.render() for node, _ in [*cycle, cycle[0]])
            + " defines a declaration in terms of itself across modules"
            + (
                " (through the holes "
                + ", ".join(sorted({".".join(hole.path) for hole in holes}))
                + ")"
                if holes
                else ""
            ),
            location,
            related=tuple(links[hole].location for hole in holes[1:]),
        )
describe_links(links: Mapping[HoleModule, ModuleIdentity]) -> str

The fillings as people read them.

PARAMETER DESCRIPTION
links

The fillings.

TYPE: Mapping[HoleModule, ModuleIdentity]

RETURNS DESCRIPTION
str

Worlds = worlds.boolean, ..., sorted by hole.

Source code in src/quivers/dsl/modules/linking.py
def describe_links(links: Mapping[HoleModule, ModuleIdentity]) -> str:
    """The fillings as people read them.

    Parameters
    ----------
    links : Mapping[HoleModule, ModuleIdentity]
        The fillings.

    Returns
    -------
    str
        ``Worlds = worlds.boolean, ...``, sorted by hole.
    """
    return ", ".join(
        f"{'.'.join(hole.path)} = {module_display(filler)}"
        for hole, filler in sorted(links.items(), key=lambda item: item[0].path)
    )

hole_closure

hole_closure(order: Iterable[ModuleIdentity], imports: Mapping[ModuleIdentity, tuple[ModuleIdentity, ...]], links: Mapping[HoleModule, ModuleIdentity]) -> dict[ModuleIdentity, tuple[HoleModule, ...]]

The holes each module needs, through imports and fillings.

PARAMETER DESCRIPTION
order

Every module of the graph.

TYPE: Iterable[ModuleIdentity]

imports

What each module imports directly (holes included).

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

links

The filler of each filled hole.

TYPE: Mapping[HoleModule, ModuleIdentity]

RETURNS DESCRIPTION
dict[ModuleIdentity, tuple[HoleModule, ...]]

Each module's holes, sorted by path: the holes it imports, the holes of the modules it imports, and the holes of the fillers of those holes, to a fixed point (fillings may be recursive).

Source code in src/quivers/dsl/modules/linking.py
def hole_closure(
    order: Iterable[ModuleIdentity],
    imports: Mapping[ModuleIdentity, tuple[ModuleIdentity, ...]],
    links: Mapping[HoleModule, ModuleIdentity],
) -> dict[ModuleIdentity, tuple[HoleModule, ...]]:
    """The holes each module needs, through imports and fillings.

    Parameters
    ----------
    order : Iterable[ModuleIdentity]
        Every module of the graph.
    imports : Mapping[ModuleIdentity, tuple[ModuleIdentity, ...]]
        What each module imports directly (holes included).
    links : Mapping[HoleModule, ModuleIdentity]
        The filler of each filled hole.

    Returns
    -------
    dict[ModuleIdentity, tuple[HoleModule, ...]]
        Each module's holes, sorted by path: the holes it imports, the
        holes of the modules it imports, and the holes of the fillers of
        those holes, to a fixed point (fillings may be recursive).
    """
    modules = list(order)
    needs: dict[ModuleIdentity, set[HoleModule]] = {module: set() for module in modules}
    changed = True
    while changed:
        changed = False
        for module in modules:
            found = set(needs[module])
            for target in imports.get(module, ()):
                if isinstance(target, HoleModule):
                    found.add(target)
                    filler = links.get(target)
                    if filler is not None:
                        found |= needs.get(filler, set())
                else:
                    found |= needs.get(target, set())
            if found != needs[module]:
                needs[module] = found
                changed = True
    return {
        module: tuple(sorted(holes, key=lambda hole: hole.path))
        for module, holes in needs.items()
    }

hole_interface

hole_interface(hole: HoleModule, signature_module: ModuleIdentity, signature_name: str, names_of: Mapping[ModuleIdentity, FileNames], trees: Mapping[ModuleIdentity, _Tree], location: SourceLocation) -> ModuleInterface

What modules importing a hole see: its signature's items.

A signature written S = Base with ... has the items of Base.

PARAMETER DESCRIPTION
hole

The hole.

TYPE: HoleModule

signature_module

The module declaring the signature.

TYPE: ModuleIdentity

signature_name

The signature's name.

TYPE: str

names_of

The loaded modules' names.

TYPE: Mapping[ModuleIdentity, FileNames]

trees

The loaded modules' parse trees, which hold a signature's definition.

TYPE: Mapping[ModuleIdentity, _Tree]

location

The hole statement, for diagnostics.

TYPE: SourceLocation

RETURNS DESCRIPTION
ModuleInterface

One entry per item, each declared by the hole itself.

RAISES DESCRIPTION
ModuleError

If the signature (or one it is defined from) is not found.

Source code in src/quivers/dsl/modules/linking.py
def hole_interface(
    hole: HoleModule,
    signature_module: ModuleIdentity,
    signature_name: str,
    names_of: Mapping[ModuleIdentity, FileNames],
    trees: Mapping[ModuleIdentity, _Tree],
    location: SourceLocation,
) -> ModuleInterface:
    """What modules importing a hole see: its signature's items.

    A signature written ``S = Base with ...`` has the items of ``Base``.

    Parameters
    ----------
    hole : HoleModule
        The hole.
    signature_module : ModuleIdentity
        The module declaring the signature.
    signature_name : str
        The signature's name.
    names_of : Mapping[ModuleIdentity, FileNames]
        The loaded modules' names.
    trees : Mapping[ModuleIdentity, _Tree]
        The loaded modules' parse trees, which hold a signature's
        definition.
    location : SourceLocation
        The ``hole`` statement, for diagnostics.

    Returns
    -------
    ModuleInterface
        One entry per item, each declared by the hole itself.

    Raises
    ------
    ModuleError
        If the signature (or one it is defined from) is not found.
    """
    seen: set[tuple[ModuleIdentity, str]] = set()
    module, name = signature_module, signature_name
    while True:
        if (module, name) in seen:
            raise module_error(
                "hole-signature",
                f"signature {name!r} is defined in terms of itself",
                location,
            )
        seen.add((module, name))
        names = names_of[module]
        vid = _signature_region(names, name)
        if vid is None:
            raise module_error(
                "hole-signature", f"no signature {name!r} in its module", location
            )
        region = names.region(vid)
        tree = trees[module]
        definition = tree.field(vid, "definition")
        base = tree.field(definition, "base") if definition is not None else None
        if base is None:
            break
        start = int(tree.consts(base)["start-byte"])
        end = int(tree.consts(base)["end-byte"])
        written = tree.source[start:end].decode("utf-8")
        module, name = resolve_signature(module, written, names_of, location)
    entries: dict[str, set[str]] = {}
    for declared in region.declarations:
        entries.setdefault(declared.name, set()).add(declared.kind)
    return ModuleInterface(
        identity=hole,
        entries=tuple(
            InterfaceEntry(
                name=item,
                origin=hole,
                origin_name=item,
                kinds=tuple(sorted(entries[item])),
            )
            for item in sorted(entries)
        ),
    )

hole_of

hole_of(path: str) -> HoleModule

The hole a dotted module path names.

PARAMETER DESCRIPTION
path

The path as a hole or link statement writes it.

TYPE: str

RETURNS DESCRIPTION
HoleModule

The hole.

RAISES DESCRIPTION
ValueError

If the path is not a module path.

Source code in src/quivers/dsl/modules/linking.py
def hole_of(path: str) -> HoleModule:
    """The hole a dotted module path names.

    Parameters
    ----------
    path : str
        The path as a ``hole`` or ``link`` statement writes it.

    Returns
    -------
    HoleModule
        The hole.

    Raises
    ------
    ValueError
        If the path is not a module path.
    """
    return HoleModule(path=parse_module_path(path))

hole_records

hole_records(names: FileNames) -> tuple[ModuleHole, ...]

The hole statements of a module, at top level only.

PARAMETER DESCRIPTION
names

The module's names.

TYPE: FileNames

RETURNS DESCRIPTION
tuple[ModuleHole, ...]

Its hole statements.

Source code in src/quivers/dsl/modules/linking.py
def hole_records(names: FileNames) -> tuple[ModuleHole, ...]:
    """The ``hole`` statements of a module, at top level only.

    Parameters
    ----------
    names : FileNames
        The module's names.

    Returns
    -------
    tuple[ModuleHole, ...]
        Its ``hole`` statements.
    """
    return names.holes
link_records(names: FileNames) -> tuple[ModuleLink, ...]

The link statements of a module.

PARAMETER DESCRIPTION
names

The module's names.

TYPE: FileNames

RETURNS DESCRIPTION
tuple[ModuleLink, ...]

Its link statements.

Source code in src/quivers/dsl/modules/linking.py
def link_records(names: FileNames) -> tuple[ModuleLink, ...]:
    """The ``link`` statements of a module.

    Parameters
    ----------
    names : FileNames
        The module's names.

    Returns
    -------
    tuple[ModuleLink, ...]
        Its ``link`` statements.
    """
    return names.links

linked_identity

linked_identity(module: ModuleIdentity, closure: Mapping[ModuleIdentity, tuple[HoleModule, ...]], links: Mapping[HoleModule, ModuleIdentity]) -> ModuleIdentity

The identity a module has in a linked program.

PARAMETER DESCRIPTION
module

A module of the graph.

TYPE: ModuleIdentity

closure

The holes each module needs (hole_closure).

TYPE: Mapping[ModuleIdentity, tuple[HoleModule, ...]]

links

The fillings.

TYPE: Mapping[HoleModule, ModuleIdentity]

RETURNS DESCRIPTION
ModuleIdentity

The module itself when it needs no hole; otherwise the module applied to the filler of each hole it needs, keyed by the hole's path. The fillers are named by their own source identities, so the identity is finite even when fillings are recursive: the whole program is linked by one map, and that map restricted to the holes the module needs is what tells two of its instances apart.

Source code in src/quivers/dsl/modules/linking.py
def linked_identity(
    module: ModuleIdentity,
    closure: Mapping[ModuleIdentity, tuple[HoleModule, ...]],
    links: Mapping[HoleModule, ModuleIdentity],
) -> ModuleIdentity:
    """The identity a module has in a linked program.

    Parameters
    ----------
    module : ModuleIdentity
        A module of the graph.
    closure : Mapping[ModuleIdentity, tuple[HoleModule, ...]]
        The holes each module needs (`hole_closure`).
    links : Mapping[HoleModule, ModuleIdentity]
        The fillings.

    Returns
    -------
    ModuleIdentity
        The module itself when it needs no hole; otherwise the module
        applied to the filler of each hole it needs, keyed by the hole's
        path. The fillers are named by their own source identities, so the
        identity is finite even when fillings are recursive: the whole
        program is linked by one map, and that map restricted to the holes
        the module needs is what tells two of its instances apart.
    """
    needed = closure.get(module, ())
    if not needed:
        return module
    return AppliedModule(
        functor=module,
        arguments=tuple(
            ModuleArgument(parameter=".".join(hole.path), module=links[hole])
            for hole in needed
        ),
    )

resolve_signature

resolve_signature(module: ModuleIdentity, reference: str, names_of: Mapping[ModuleIdentity, FileNames], location: SourceLocation) -> tuple[ModuleIdentity, str]

Find the signature a hole names, from the declaring module's text.

A hole's signature is found before any module is checked, since the modules importing the hole are checked against it. S names a signature the module declares; L.S (or a.b.S) names one that the module imported as L (or as a.b) declares.

PARAMETER DESCRIPTION
module

The module whose hole statement names the signature.

TYPE: ModuleIdentity

reference

The signature as written.

TYPE: str

names_of

The loaded modules' names.

TYPE: Mapping[ModuleIdentity, FileNames]

location

The hole statement, for diagnostics.

TYPE: SourceLocation

RETURNS DESCRIPTION
tuple[ModuleIdentity, str]

The declaring module and the signature's name there.

RAISES DESCRIPTION
ModuleError

With code hole-signature if the reference names no signature.

Source code in src/quivers/dsl/modules/linking.py
def resolve_signature(
    module: ModuleIdentity,
    reference: str,
    names_of: Mapping[ModuleIdentity, FileNames],
    location: SourceLocation,
) -> tuple[ModuleIdentity, str]:
    """Find the signature a hole names, from the declaring module's text.

    A hole's signature is found before any module is checked, since the
    modules importing the hole are checked against it. ``S`` names a
    signature the module declares; ``L.S`` (or ``a.b.S``) names one that
    the module imported as ``L`` (or as ``a.b``) declares.

    Parameters
    ----------
    module : ModuleIdentity
        The module whose ``hole`` statement names the signature.
    reference : str
        The signature as written.
    names_of : Mapping[ModuleIdentity, FileNames]
        The loaded modules' names.
    location : SourceLocation
        The ``hole`` statement, for diagnostics.

    Returns
    -------
    tuple[ModuleIdentity, str]
        The declaring module and the signature's name there.

    Raises
    ------
    ModuleError
        With code ``hole-signature`` if the reference names no signature.
    """
    names = names_of[module]
    head, _, last = reference.rpartition(".")
    candidates: list[ModuleIdentity] = []
    if not head:
        candidates.append(module)
        candidates.extend(
            SourceModule(path=parse_module_path(record.path))
            for record in names.imports
            if record.items is not None
            and any(item.name == last for item in record.items)
        )
    else:
        candidates.extend(
            SourceModule(path=parse_module_path(record.path))
            for record in names.imports
            if head in (record.alias, record.path)
        )
    for candidate in candidates:
        found = names_of.get(candidate)
        if found is not None and _signature_region(found, last) is not None:
            return candidate, last
    known = [
        region.name
        for region in names.regions
        if region.kind == "signature" and not region.parent
    ]
    raise module_error(
        "hole-signature",
        f"{reference!r} names no signature a hole can have: a hole's signature is "
        "declared in the module of the `hole` statement or in a module it imports",
        location,
        suggestions=near_misses(reference, known),
    )

unfilled

unfilled(closure: Mapping[ModuleIdentity, tuple[HoleModule, ...]], links: Mapping[HoleModule, ModuleIdentity], module: ModuleIdentity) -> tuple[HoleModule, ...]

The holes a module needs that no link fills.

PARAMETER DESCRIPTION
closure

The holes each module needs.

TYPE: Mapping[ModuleIdentity, tuple[HoleModule, ...]]

links

The fillings.

TYPE: Mapping[HoleModule, ModuleIdentity]

module

The module.

TYPE: ModuleIdentity

RETURNS DESCRIPTION
tuple[HoleModule, ...]

The unfilled holes, sorted by path.

Source code in src/quivers/dsl/modules/linking.py
def unfilled(
    closure: Mapping[ModuleIdentity, tuple[HoleModule, ...]],
    links: Mapping[HoleModule, ModuleIdentity],
    module: ModuleIdentity,
) -> tuple[HoleModule, ...]:
    """The holes a module needs that no link fills.

    Parameters
    ----------
    closure : Mapping[ModuleIdentity, tuple[HoleModule, ...]]
        The holes each module needs.
    links : Mapping[HoleModule, ModuleIdentity]
        The fillings.
    module : ModuleIdentity
        The module.

    Returns
    -------
    tuple[HoleModule, ...]
        The unfilled holes, sorted by path.
    """
    return tuple(hole for hole in closure.get(module, ()) if hole not in links)

address_segments

address_segments(path: str) -> tuple[str, ...]

Split an address at the dots that are not inside an instantiation.

PARAMETER DESCRIPTION
path

A rendered address or pattern.

TYPE: str

RETURNS DESCRIPTION
tuple[str, ...]

The segments: Discourse(Lexicon.Core,W).fit.prior splits into Discourse(Lexicon.Core,W), fit, prior.

RAISES DESCRIPTION
SiteError

If the parentheses do not balance.

Source code in src/quivers/dsl/modules/sites.py
def address_segments(path: str) -> tuple[str, ...]:
    """Split an address at the dots that are not inside an instantiation.

    Parameters
    ----------
    path : str
        A rendered address or pattern.

    Returns
    -------
    tuple[str, ...]
        The segments: ``Discourse(Lexicon.Core,W).fit.prior`` splits into
        ``Discourse(Lexicon.Core,W)``, ``fit``, ``prior``.

    Raises
    ------
    SiteError
        If the parentheses do not balance.
    """
    segments: list[str] = []
    depth = 0
    start = 0
    for index, char in enumerate(path):
        if char == "(":
            depth += 1
        elif char == ")":
            depth -= 1
            if depth < 0:
                raise SiteError(f"unbalanced ')' in {path!r}")
        elif char == MEMBER_SEPARATOR and depth == 0:
            segments.append(path[start:index])
            start = index + 1
    if depth:
        raise SiteError(f"unbalanced '(' in {path!r}")
    segments.append(path[start:])
    return tuple(segments)

site_table

site_table(module: QiecModule, entry: str, *, root: str | None = None, ties: SiteTies | None = None) -> SiteTable

The sites and parameters of one program of a checked module.

PARAMETER DESCRIPTION
module

The checked module of a flat program.

TYPE: QiecModule

entry

The program's flat-program name.

TYPE: str

root

The root module's path, which addresses the root's own declarations; the checked module's name when omitted.

TYPE: str | None DEFAULT: None

ties

Declared sharing; a tied site or parameter takes the identity and address of the one it is tied to.

TYPE: SiteTies | None DEFAULT: None

RETURNS DESCRIPTION
SiteTable

The program's sample sites, in step order, then every learned parameter of the module, by key.

RAISES DESCRIPTION
SiteError

If the module has no such program.

Source code in src/quivers/dsl/modules/sites.py
def site_table(
    module: QiecModule,
    entry: str,
    *,
    root: str | None = None,
    ties: SiteTies | None = None,
) -> SiteTable:
    """The sites and parameters of one program of a checked module.

    Parameters
    ----------
    module : QiecModule
        The checked module of a flat program.
    entry : str
        The program's flat-program name.
    root : str | None
        The root module's path, which addresses the root's own
        declarations; the checked module's name when omitted.
    ties : SiteTies | None
        Declared sharing; a tied site or parameter takes the identity and
        address of the one it is tied to.

    Returns
    -------
    SiteTable
        The program's sample sites, in step order, then every learned
        parameter of the module, by key.

    Raises
    ------
    SiteError
        If the module has no such program.
    """
    root_path = module.module if root is None else root
    declared = ties or SiteTies()
    identities = _Identities(module)
    program = _entry(module, entry)
    records: list[SiteRecord] = []
    for site in program.sites:
        declaration, label = declared.site(entry, site.name)
        identity = identities.site(declaration, label)
        module_path, local = _split(declaration, root_path)
        records.append(
            SiteRecord(
                address=SiteAddress(module=module_path, declaration=local, label=label),
                kind=site.kind,
                identity=identity,
                key=site.name,
                target=target_identifier(site.name),
            )
        )
    parameters = {name.spelled(): name for name in _parameter_names(module)}
    for key in sorted(parameters):
        name = parameters[key]
        owner = declared.owner(name.owner)
        module_path, local = _split(owner, root_path)
        records.append(
            SiteRecord(
                address=SiteAddress(
                    module=module_path, declaration=local, label=name.member
                ),
                kind="parameter",
                identity=identities.parameter(owner, name.member),
                key=key,
                target=key,
            )
        )
    return SiteTable(entry=entry, sites=tuple(records))

site_ties

site_ties(module: Module) -> SiteTies

The sharing a flat program's share statements declare.

Each side of a share is a path, resolved to a flat-program name, of a program's sample site (A.fit.prior), of a whole program (every sample site of it, by label), or of a deduction (its learned parameters). Two sample sites are one site only when they are drawn from the same family over the same plate and axes, so they have one type and one support; two deductions share their parameters only when they declare the same productions, so each parameter has one counterpart.

PARAMETER DESCRIPTION
module

The flat program.

TYPE: Module

RETURNS DESCRIPTION
SiteTies

The ties, in statement order.

RAISES DESCRIPTION
ShareError

If a path names no program site or deduction, the two sides are of different kinds, a site lacks its counterpart, or the counterparts differ in type, support, or productions.

Source code in src/quivers/dsl/modules/sites.py
def site_ties(module: Module) -> SiteTies:
    """The sharing a flat program's ``share`` statements declare.

    Each side of a ``share`` is a path, resolved to a flat-program name, of
    a program's sample site (``A.fit.prior``), of a whole program (every
    sample site of it, by label), or of a deduction (its learned
    parameters). Two sample sites are one site only when they are drawn
    from the same family over the same plate and axes, so they have one
    type and one support; two deductions share their parameters only when
    they declare the same productions, so each parameter has one
    counterpart.

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

    Returns
    -------
    SiteTies
        The ties, in statement order.

    Raises
    ------
    ShareError
        If a path names no program site or deduction, the two sides are of
        different kinds, a site lacks its counterpart, or the counterparts
        differ in type, support, or productions.
    """
    programs = {
        statement.name: statement
        for statement in module.statements
        if isinstance(statement, ProgramDecl)
    }
    deductions = {
        statement.name: statement
        for statement in module.statements
        if isinstance(statement, DeductionDecl)
    }
    names = sorted({*programs, *deductions}, key=len, reverse=True)

    def resolve(path: str, statement: ShareDecl) -> tuple[str, str]:
        for name in names:
            if path == name:
                return name, ""
            if path.startswith(name + MEMBER_SEPARATOR):
                return name, path[len(name) + 1 :]
        raise ShareError(
            f"{source_spelling(path)!r} names no program, program site, or deduction",
            statement,
        )

    sites: list[SiteTie] = []
    owners: list[OwnerTie] = []
    for statement in module.statements:
        if not isinstance(statement, ShareDecl):
            continue
        tied, member = resolve(statement.site, statement)
        target, target_member = resolve(statement.target, statement)
        shown = f"{source_spelling(statement.site)} with {source_spelling(statement.target)}"
        if (tied, member) == (target, target_member):
            raise ShareError(f"cannot share {shown}: a site is itself", statement)
        if tied in deductions or target in deductions:
            if tied not in deductions or target not in deductions:
                raise ShareError(
                    f"cannot share {shown}: one side is a deduction's parameters "
                    "and the other is not",
                    statement,
                )
            if member or target_member:
                raise ShareError(
                    f"cannot share {shown}: a deduction's learned parameters are "
                    "one family indexed by its productions, so they are shared as "
                    f"a whole, as in `share {source_spelling(tied)} with "
                    f"{source_spelling(target)}`",
                    statement,
                )
            if _scrubbed(deductions[tied].with_(name=target)) != _scrubbed(
                deductions[target]
            ):
                raise ShareError(
                    f"cannot share {shown}: the deductions declare different "
                    "productions, so their parameters do not correspond",
                    statement,
                )
            owners.append(OwnerTie(owner=tied, target=target))
            continue
        if bool(member) != bool(target_member):
            raise ShareError(
                f"cannot share {shown}: one side is a site and the other a "
                "whole program",
                statement,
            )
        labels = (
            ((member, target_member),)
            if member
            else tuple(
                (step.vars[0], step.vars[0])
                for step in programs[tied].draws
                if isinstance(step, SampleStep)
                and step.operation == "sample"
                and len(step.vars) == 1
            )
        )
        for label, target_label in labels:
            step = _sample_step(programs[tied], label)
            other = _sample_step(programs[target], target_label)
            if step is None or other is None:
                missing = (
                    f"{source_spelling(tied)}.{label}"
                    if step is None
                    else f"{source_spelling(target)}.{target_label}"
                )
                raise ShareError(
                    f"cannot share {shown}: {missing} is not a sample site", statement
                )
            if _support(step) != _support(other):
                raise ShareError(
                    f"cannot share {shown}: {source_spelling(tied)}.{label} is "
                    f"drawn from {step.morphism} and "
                    f"{source_spelling(target)}.{target_label} from "
                    f"{other.morphism} (or over another plate), so they differ "
                    "in type or support",
                    statement,
                )
            sites.append(
                SiteTie(
                    declaration=tied,
                    label=label,
                    target_declaration=target,
                    target_label=target_label,
                )
            )
    return SiteTies(sites=tuple(sites), owners=tuple(owners))

module_name_resolver

module_name_resolver(graph: ModuleGraph, identity: ModuleIdentity, line_offset: int) -> NameResolver

Resolve names as a file-level module of a graph resolves identifiers.

PARAMETER DESCRIPTION
graph

The checked graph.

TYPE: ModuleGraph

identity

A module of the graph.

TYPE: ModuleIdentity

line_offset

How far the module's lines are shifted in the flat program, so a diagnostic points into the module's own file.

TYPE: int

RETURNS DESCRIPTION
NameResolver

Maps a name written at a flat-program line and column to the flat name of what it denotes: a declaration of the module, or a member of a module it imports, possibly with a generated member path such as G.Item. None when the module binds no such name, or when the name denotes a module or reads a field of a value.

RAISES DESCRIPTION
ModuleError

From the returned resolver, when a name selects a member that its module does not have or does not export.

Source code in src/quivers/dsl/modules/quoted_names.py
def module_name_resolver(
    graph: ModuleGraph, identity: ModuleIdentity, line_offset: int
) -> NameResolver:
    """Resolve names as a file-level module of a graph resolves identifiers.

    Parameters
    ----------
    graph : ModuleGraph
        The checked graph.
    identity : ModuleIdentity
        A module of the graph.
    line_offset : int
        How far the module's lines are shifted in the flat program, so a
        diagnostic points into the module's own file.

    Returns
    -------
    NameResolver
        Maps a name written at a flat-program line and column to the flat
        name of what it denotes: a declaration of the module, or a member
        of a module it imports, possibly with a generated member path such
        as ``G.Item``. ``None`` when the module binds no such name, or when
        the name denotes a module or reads a field of a value.

    Raises
    ------
    ModuleError
        From the returned resolver, when a name selects a member that its
        module does not have or does not export.
    """
    checked = graph.checked[identity]
    interfaces = {item.module: graph.interface(item.module) for item in checked.imports}
    private = {
        item.module: (
            frozenset()
            if isinstance(item.module, HoleModule)
            else frozenset(
                declared.name
                for declared in graph.loaded[item.module].names.declarations
            )
            - frozenset(graph.checked[item.module].interface.names())
        )
        for item in checked.imports
    }
    scope = file_scope(
        checked.source, checked.names, checked.imports, interfaces, private
    )

    def resolve(text: str, line: int, col: int) -> str | None:
        """Resolve one written name.

        Parameters
        ----------
        text : str
            The name, possibly dotted.
        line : int
            Its flat-program line.
        col : int
            Its column.

        Returns
        -------
        str | None
            Its flat name, or ``None`` when the module binds no such name
            or the text is not a name as source writes one (a flat name
            such as ``grammar.ccg:Atom`` is already resolved).
        """
        if not _WRITTEN_NAME.fullmatch(text):
            return None
        occurrence = Occurrence(
            start=0,
            end=len(text.encode("utf-8")),
            text=text,
            role="reference",
            parent_kind="",
            field="",
            statement=0,
            line=max(line - line_offset, 1),
            column=col,
        )
        resolution = resolve_occurrence(scope, occurrence)
        if resolution is None or resolution.symbol is None or resolution.members:
            return None
        symbol = resolution.symbol
        flat = (
            symbol.name
            if symbol.module == graph.root
            else flat_name(symbol.module, symbol.name)
        )
        return member_name(flat, *resolution.path) if resolution.path else flat

    return resolve

resolve_quoted_names

resolve_quoted_names(statement: Statement, resolve: NameResolver, *, names: NameParameters) -> Statement

Resolve every string literal a statement writes as a quoted name.

A literal is a quoted name when it is written at a quoted-name position of a quoted-syntax constructor (QUOTED_NAME_POSITIONS), as the argument of a computation's name parameter (NameParameters), or as the value of a let whose variable reaches either.

PARAMETER DESCRIPTION
statement

A statement of one module, typically a meta declaration or a splice.

TYPE: Statement

resolve

Resolution in that module's scope.

TYPE: NameResolver

names

The name parameters of every computation the statement can call.

TYPE: NameParameters

RETURNS DESCRIPTION
Statement

The statement with each such literal replaced by the flat name it resolves to; literals the module does not bind are unchanged.

Source code in src/quivers/dsl/modules/quoted_names.py
def resolve_quoted_names(
    statement: Statement, resolve: NameResolver, *, names: NameParameters
) -> Statement:
    """Resolve every string literal a statement writes as a quoted name.

    A literal is a quoted name when it is written at a quoted-name position
    of a quoted-syntax constructor (`QUOTED_NAME_POSITIONS`), as the
    argument of a computation's name parameter (`NameParameters`), or as
    the value of a ``let`` whose variable reaches either.

    Parameters
    ----------
    statement : Statement
        A statement of one module, typically a meta declaration or a splice.
    resolve : NameResolver
        Resolution in that module's scope.
    names : NameParameters
        The name parameters of every computation the statement can call.

    Returns
    -------
    Statement
        The statement with each such literal replaced by the flat name it
        resolves to; literals the module does not bind are unchanged.
    """
    rewritten = _rewrite(statement, resolve, names, frozenset(), None)
    assert isinstance(rewritten, Statement)
    return rewritten

check_module

check_module(source: ModuleSource, names: FileNames, imports: tuple[ResolvedImport, ...], interfaces: Mapping[ModuleIdentity, ModuleInterface], private_names: Mapping[ModuleIdentity, frozenset[str]]) -> CheckedModule

Resolve every name of one module against its imports' interfaces.

Only the interfaces of the module's dependencies are read, never their bodies; private_names serves diagnostics alone (to say that a name exists but is private).

PARAMETER DESCRIPTION
source

The module's source.

TYPE: ModuleSource

names

Its name occurrences.

TYPE: FileNames

imports

Its imports, each with the module it names.

TYPE: tuple[ResolvedImport, ...]

interfaces

The interface of every module it imports.

TYPE: Mapping[ModuleIdentity, ModuleInterface]

private_names

The names each imported module declares without exporting.

TYPE: Mapping[ModuleIdentity, frozenset[str]]

RETURNS DESCRIPTION
CheckedModule

The resolutions and the module's interface.

RAISES DESCRIPTION
ModuleError

On an unknown, private, unimported, or ambiguous name, a clashing alias, an unknown open, or a malformed export.

Source code in src/quivers/dsl/modules/resolve.py
def check_module(
    source: ModuleSource,
    names: FileNames,
    imports: tuple[ResolvedImport, ...],
    interfaces: Mapping[ModuleIdentity, ModuleInterface],
    private_names: Mapping[ModuleIdentity, frozenset[str]],
) -> CheckedModule:
    """Resolve every name of one module against its imports' interfaces.

    Only the interfaces of the module's dependencies are read, never their
    bodies; ``private_names`` serves diagnostics alone (to say that a name
    exists but is private).

    Parameters
    ----------
    source : ModuleSource
        The module's source.
    names : FileNames
        Its name occurrences.
    imports : tuple[ResolvedImport, ...]
        Its imports, each with the module it names.
    interfaces : Mapping[ModuleIdentity, ModuleInterface]
        The interface of every module it imports.
    private_names : Mapping[ModuleIdentity, frozenset[str]]
        The names each imported module declares without exporting.

    Returns
    -------
    CheckedModule
        The resolutions and the module's interface.

    Raises
    ------
    ModuleError
        On an unknown, private, unimported, or ambiguous name, a clashing
        alias, an unknown ``open``, or a malformed ``export``.
    """
    scope = _Scope(source, names, interfaces, imports, private_names)
    return _checked(scope, names)

load_file_graph

load_file_graph(path: str | Path, *, roots: tuple[str | Path, ...] | None = None, loader: ModuleLoader | None = None, links: Mapping[str, str] | None = None) -> ModuleGraph

Load and check the module graph rooted at a file.

PARAMETER DESCRIPTION
path

The root module's file.

TYPE: str | Path

roots

The directories module paths are relative to; the file's own directory when omitted.

TYPE: tuple[str | Path, ...] | None DEFAULT: None

loader

Consulted before the roots, for sources not on disk (an editor's unsaved buffers).

TYPE: ModuleLoader | None DEFAULT: None

links

Fillings of the package's holes, hole path to module path, besides the graph's own link statements.

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

RETURNS DESCRIPTION
ModuleGraph

The checked graph.

RAISES DESCRIPTION
OSError

If the file cannot be read.

ValueError

If the file lies below none of the roots.

ModuleError

If the graph does not load or a name does not resolve.

Source code in src/quivers/dsl/modules/__init__.py
def load_file_graph(
    path: str | Path,
    *,
    roots: tuple[str | Path, ...] | None = None,
    loader: ModuleLoader | None = None,
    links: Mapping[str, str] | None = None,
) -> ModuleGraph:
    """Load and check the module graph rooted at a file.

    Parameters
    ----------
    path : str | Path
        The root module's file.
    roots : tuple[str | Path, ...] | None
        The directories module paths are relative to; the file's own
        directory when omitted.
    loader : ModuleLoader | None
        Consulted before the roots, for sources not on disk (an editor's
        unsaved buffers).
    links : Mapping[str, str] | None
        Fillings of the package's holes, hole path to module path, besides
        the graph's own ``link`` statements.

    Returns
    -------
    ModuleGraph
        The checked graph.

    Raises
    ------
    OSError
        If the file cannot be read.
    ValueError
        If the file lies below none of the roots.
    ModuleError
        If the graph does not load or a name does not resolve.
    """
    file = Path(path).resolve()
    search = tuple(Path(root).resolve() for root in roots) if roots else (file.parent,)
    files = FileSystemLoader(search)
    module_path = files.root_path_of(file)
    root = ModuleSource(
        identity=SourceModule(path=module_path),
        label=str(path),
        text=read_module_text(file),
        file=str(file),
    )
    return load_graph(root, _loader(search, loader), links=links)

interpret_file

interpret_file(path: str | Path, *, roots: tuple[str | Path, ...] | None = None, loader: ModuleLoader | None = None, links: Mapping[str, str] | None = None) -> FlatProgram

Interpret the module graph rooted at a file as one flat program.

PARAMETER DESCRIPTION
path

The root module's file.

TYPE: str | Path

roots

The directories module paths are relative to; the file's own directory when omitted.

TYPE: tuple[str | Path, ...] | None DEFAULT: None

loader

Consulted before the roots.

TYPE: ModuleLoader | None DEFAULT: None

links

Fillings of the package's holes, hole path to module path, besides the graph's own link statements.

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

RETURNS DESCRIPTION
FlatProgram

The flat program.

RAISES DESCRIPTION
OSError

If the file cannot be read.

ValueError

If the file lies below none of the roots.

ModuleError

If the graph does not load or a name does not resolve.

Source code in src/quivers/dsl/modules/__init__.py
def interpret_file(
    path: str | Path,
    *,
    roots: tuple[str | Path, ...] | None = None,
    loader: ModuleLoader | None = None,
    links: Mapping[str, str] | None = None,
) -> FlatProgram:
    """Interpret the module graph rooted at a file as one flat program.

    Parameters
    ----------
    path : str | Path
        The root module's file.
    roots : tuple[str | Path, ...] | None
        The directories module paths are relative to; the file's own
        directory when omitted.
    loader : ModuleLoader | None
        Consulted before the roots.
    links : Mapping[str, str] | None
        Fillings of the package's holes, hole path to module path, besides
        the graph's own ``link`` statements.

    Returns
    -------
    FlatProgram
        The flat program.

    Raises
    ------
    OSError
        If the file cannot be read.
    ValueError
        If the file lies below none of the roots.
    ModuleError
        If the graph does not load or a name does not resolve.
    """
    return interpret(load_file_graph(path, roots=roots, loader=loader, links=links))

interpret_module

interpret_module(module_path: str, *, roots: tuple[str | Path, ...] = (Path('.'),), loader: ModuleLoader | None = None, links: Mapping[str, str] | None = None) -> FlatProgram

Interpret the module graph rooted at a module path.

PARAMETER DESCRIPTION
module_path

The root module's dotted path, e.g. pkg.experiments.boolean.

TYPE: str

roots

The directories module paths are relative to.

TYPE: tuple[str | Path, ...] DEFAULT: (Path('.'),)

loader

Consulted before the roots.

TYPE: ModuleLoader | None DEFAULT: None

links

Fillings of the package's holes, hole path to module path, besides the graph's own link statements.

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

RETURNS DESCRIPTION
FlatProgram

The flat program.

RAISES DESCRIPTION
ModuleError

If no root (or more than one) provides the module, or the graph does not load or resolve.

Source code in src/quivers/dsl/modules/__init__.py
def interpret_module(
    module_path: str,
    *,
    roots: tuple[str | Path, ...] = (Path("."),),
    loader: ModuleLoader | None = None,
    links: Mapping[str, str] | None = None,
) -> FlatProgram:
    """Interpret the module graph rooted at a module path.

    Parameters
    ----------
    module_path : str
        The root module's dotted path, e.g. ``pkg.experiments.boolean``.
    roots : tuple[str | Path, ...]
        The directories module paths are relative to.
    loader : ModuleLoader | None
        Consulted before the roots.
    links : Mapping[str, str] | None
        Fillings of the package's holes, hole path to module path, besides
        the graph's own ``link`` statements.

    Returns
    -------
    FlatProgram
        The flat program.

    Raises
    ------
    ModuleError
        If no root (or more than one) provides the module, or the graph
        does not load or resolve.
    """
    search = tuple(Path(root).resolve() for root in roots)
    combined = _loader(search, loader)
    path = parse_module_path(module_path)
    found: tuple[ModuleSource, ...] = combined.find(path)
    location = SourceLocation(file=module_path)
    if not found:
        raise ModuleError(
            ModuleDiagnostic(
                code="module-unknown",
                message=f"no module {module_path} below "
                + ", ".join(str(root) for root in search),
                location=location,
                suggestions=near_misses(module_path, combined.available()),
            )
        )
    if len(found) > 1:
        raise ModuleError(
            ModuleDiagnostic(
                code="module-ambiguous-path",
                message=f"module {module_path} is provided by "
                + " and by ".join(item.label for item in found),
                location=location,
            )
        )
    source = next(iter(found))
    return interpret(load_graph(source, combined, links=links))

interpret_source

interpret_source(text: str, *, label: str = '<source>', module_path: str = ROOT_MODULE_NAME, loader: ModuleLoader | None = None, roots: tuple[str | Path, ...] = (), links: Mapping[str, str] | None = None) -> FlatProgram

Interpret source text, as the root module, with its imports.

PARAMETER DESCRIPTION
text

The root module's source.

TYPE: str

label

The label its diagnostics name.

TYPE: str DEFAULT: '<source>'

module_path

The root module's path.

TYPE: str DEFAULT: ROOT_MODULE_NAME

loader

Finds the modules it imports.

TYPE: ModuleLoader | None DEFAULT: None

roots

Directories searched after loader.

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

links

Fillings of the package's holes, hole path to module path, besides the graph's own link statements.

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

RETURNS DESCRIPTION
FlatProgram

The flat program.

RAISES DESCRIPTION
ModuleError

If the graph does not load or a name does not resolve.

Source code in src/quivers/dsl/modules/__init__.py
def interpret_source(
    text: str,
    *,
    label: str = "<source>",
    module_path: str = ROOT_MODULE_NAME,
    loader: ModuleLoader | None = None,
    roots: tuple[str | Path, ...] = (),
    links: Mapping[str, str] | None = None,
) -> FlatProgram:
    """Interpret source text, as the root module, with its imports.

    Parameters
    ----------
    text : str
        The root module's source.
    label : str
        The label its diagnostics name.
    module_path : str
        The root module's path.
    loader : ModuleLoader | None
        Finds the modules it imports.
    roots : tuple[str | Path, ...]
        Directories searched after ``loader``.
    links : Mapping[str, str] | None
        Fillings of the package's holes, hole path to module path, besides
        the graph's own ``link`` statements.

    Returns
    -------
    FlatProgram
        The flat program.

    Raises
    ------
    ModuleError
        If the graph does not load or a name does not resolve.
    """
    search = tuple(Path(root).resolve() for root in roots)
    combined = _loader(search, loader)
    root = ModuleSource(
        identity=SourceModule(path=parse_module_path(module_path)),
        label=label,
        text=text,
    )
    return interpret(load_graph(root, combined, links=links))

interpret

Static interpretation of a module graph into one flat program.

Compilation never sees modules. Every module of the graph is walked into statements whose names are already resolved, and the statements are concatenated, dependencies first, into one flat Module, so the compiler, the reference machine, and every transpile target see a single, fully qualified program.

A module reached only through meta import serves the meta phase: its computations, families, and index sorts enter the flat program as meta declarations and its other declarations do not enter it.

A declaration of the root module keeps its name; a declaration of any other module is named by the module and its name, syntax.lambda:Term (quivers.qiec.names.module_qualified). A module reached along two import paths is walked once, so its declarations appear once. The imported modules' lines are numbered after the root's, and the SourceMap maps a line of the flat program back to its file.

interpret

interpret(graph: ModuleGraph) -> FlatProgram

Interpret a checked module graph as one flat program.

PARAMETER DESCRIPTION
graph

The loaded, checked graph.

TYPE: ModuleGraph

RETURNS DESCRIPTION
FlatProgram

The flat program and its source map.

Source code in src/quivers/dsl/modules/interpret.py
def interpret(graph: ModuleGraph) -> FlatProgram:
    """Interpret a checked module graph as one flat program.

    Parameters
    ----------
    graph : ModuleGraph
        The loaded, checked graph.

    Returns
    -------
    FlatProgram
        The flat program and its source map.
    """
    root_source = graph.loaded[graph.root].source
    spans = [
        SourceSpan(
            module=graph.root,
            label=root_source.label,
            first_line=1,
            line_count=_line_count(root_source.text),
        )
    ]
    next_line = 1 + _line_count(root_source.text)
    offsets: dict[ModuleIdentity, int] = {graph.root: 0}
    for identity in graph.order:
        if identity == graph.root:
            continue
        source = graph.loaded[identity].source
        offsets[identity] = next_line - 1
        spans.append(
            SourceSpan(
                module=identity,
                label=source.label,
                first_line=next_line,
                line_count=_line_count(source.text),
            )
        )
        next_line += _line_count(source.text)
    statements: list[Statement] = []
    tests = ()
    experiments = ()
    phase_one = meta_only_modules(graph)
    interfaces = {
        identity: graph.checked[identity].interface for identity in graph.order
    }
    if uses_module_language(graph):
        return _interpret_module_language(
            graph, offsets, phase_one, interfaces, spans, next_line
        )
    names = NameParameters()
    for identity in graph.order:
        loaded = graph.loaded[identity]
        checked = graph.checked[identity]
        loaded.tree.set_view(name_view(checked, graph.root, offsets[identity]))
        walked = walk_tree(loaded.tree, checked.names, loaded.source.label)
        if has_notation_surface(walked):
            scoped, scoped_tests = scope_module_notation(
                walked.statements,
                walked.tests,
                ModuleNotations(checked, interfaces, graph.root),
            )
            if identity != graph.root:
                # A dependency's activations scoped its own quotations; only
                # the root's decide the program's printing.
                scoped = tuple(
                    item for item in scoped if not isinstance(item, OpenNotationDecl)
                )
            walked = walked.with_(statements=scoped, tests=scoped_tests)
        is_root = identity == graph.root
        names = names.learn(walked.statements)
        hygiene = _Hygiene(graph, identity, offsets[identity], names)
        for statement in walked.statements:
            if isinstance(statement, MODULE_STATEMENT_TYPES):
                continue
            if not is_root and isinstance(statement, ExportDecl):
                continue
            if identity in phase_one:
                if isinstance(
                    statement, QiecComputationDecl | QiecFamilyDecl | QiecIndexDecl
                ):
                    statements.append(
                        hygiene.apply(
                            MetaDecl(
                                declaration=statement,
                                line=statement.line,
                                col=statement.col,
                            )
                        )
                    )
                continue
            statements.append(hygiene.apply(statement))
        if is_root:
            tests = walked.tests
            experiments = walked.experiments
    spellings = root_spellings(statements, graph.checked[graph.root])
    if spellings is not None:
        statements.append(spellings)
    return FlatProgram(
        module=Module(
            statements=tuple(statements), tests=tests, experiments=experiments
        ),
        root=graph.root,
        source_map=SourceMap(spans=tuple(spans)),
        interfaces=tuple(graph.checked[identity].interface for identity in graph.order),
    )