Skip to content

CLI: qvr

The qvr console script ships with the package as a thin wrapper around the parser, the constraint solver, and the compiler. check validates source files, run runs one entry point, transpile writes target source, and repl and lsp give interactive and editor access. Fitting a posterior with stochastic variational inference (SVI) or Markov chain Monte Carlo (MCMC) goes through the inference API.

qvr check FILES...

Parse, run the constraint solver on, and compile every .qvr file given. The command emits structured diagnostics and exits with 0 on full success and 1 on any error.

Flags:

  • --json: emit a single JSON document on stdout containing the full diagnostic list, as expected by CI and pre-commit hooks.
  • --target TARGET: compare every checked Quivers Indexed Effect Core (QIEC) computation with the selected transpiler's advertised capabilities. Unsupported features are errors, so this mode serves as an early release gate for one target. It does not render the target program, so qvr transpile --to TARGET FILE remains the check of the whole lowering and rendering path.

Diagnostic codes:

  • parse: tree-sitter rejected the source.
  • compile: the compiler raised CompileError.
  • residuated_constraint: a slash category appears outside a residuated context, that is, outside a schema parameterized by a declared FreeResiduated set of categories.
  • effect_constraint: an applied effect has a name that neither starts with an uppercase letter nor contains an underscore.
  • bundle_unknown_member: a bundle declaration names a member that is not a declared rule, schema, bundle, or built-in schema.
  • family-arg-shape: a distribution call has the wrong number of arguments or incompatible argument shapes.
  • implicit-family-defaults: a distribution call relies on deprecated implicit defaults. This diagnostic is a warning.
  • qiec-route: the didactic lowering route from the QVR source protocol to the QIEC core ABI is unavailable or does not match.
  • qiec-kind: a static argument or binder has the wrong kind.
  • qiec-index: an index expression has the wrong sort or constructor shape.
  • qiec-row: an effect row violates instance identity, unification, or a lacks constraint.
  • qiec-coverage: indexed case branches are incomplete, duplicated, or not justified by refinement.
  • qiec-skolem-escape: static evidence local to a branch escapes its scope.
  • qiec-handler: a handler signature violates coverage, forwarding, or resumption requirements.
  • qiec-unhandled-effect: a computation performs an instance absent from its declared row.
  • qiec-backend: a requested backend boundary cannot preserve a QIEC form.
  • qiec:capability:FEATURE:COMPUTATION: --target selected a backend that cannot preserve FEATURE in the named computation.
  • io: a file-system error, such as a missing or unreadable file.

qvr migrate PATHS...

Lower .qvr source forward along the QVR grammar release chain. The composer chains the migrators between adjacent grammar releases defined in quivers.cli.migrations, so the intermediate releases need not be named. --from and --to select part of the chain.

Flags:

  • --from VERSION: required source revision in the chain. QVR files do not encode an unambiguous grammar version.
  • --to VERSION: target revision (defaults to HEAD).
  • --dry-run: report which files would change without writing.
  • --output DIR: write migrated copies under DIR instead of overwriting the originals.
  • --check: compare each adjacent grammar pair with its migrator and fail if a removed rule has no converter. This mode does not migrate files.
  • --dependency PKG@OLD..NEW: migrate the modules of the package containing the working directory (or --package DIR), and the run records given as paths, from the locked version of a dependency to the version its manifest now resolves to, along the dependency's interface lens (migrating dependents of a package). Every place that names a removed symbol is listed with its location and its file is left unchanged; the exit status is then 1.

Directory arguments are walked recursively, and individual .qvr files may also be given. Markdown files, including literate .qvr.md modules, are migrated block by block: each fenced qvr block is rewritten in place according to its <!-- compile: ... --> marker, and every compile: false fragment is listed as review PATH:LINE for a reader to check. The migration tooling is built on the in-tree panproto VCS at grammars/qvr/vcs/. A new release adds a migration without changing the earlier migration steps.

qvr lock, qvr build, qvr bump, qvr publish

The package commands (packages, lockfiles, and versions) work on the package containing the working directory, or the one --package DIR names.

  • qvr lock: resolve qvr.toml by minimal version selection, check every module of every package, and write qvr.lock with each module's content hashes. A resolution failure prints its derivation.
  • qvr build: resolve against qvr.lock (offline once its commits are cached), refuse a stale lockfile (package-lock-stale) or a module whose hashes differ from their pins (package-pin-mismatch), and check every module of the package.
  • qvr bump --against REF: compare the package's interface with the version at REF (a directory or a git revision of its repository) and print every change with the version it requires. --to VERSION checks a version, --write writes the required one into qvr.toml, and --json prints the changes as data. A version that understates the change exits 1; a major change writes its dependency lens into lenses/.
  • qvr publish INDEX --git URL [--rev REV]: check and pin the package at a commit of its repository and commit its entry into INDEX, a working tree of a package index, refusing a version that is already listed or that understates its change from the newest listed one. --cache DIR names the git cache.

Each exits with 0 on success and 1 on a refusal, printing qvr: <message>.

qvr repl [FILE] [--plain] [--target TARGET]

Start the interactive REPL. Without a file, the REPL opens an empty session. With a file, it loads and elaborates the file before showing the prompt. --plain uses the plain front end that reads one line at a time instead of the TUI, and --target TARGET makes every load report the capability diagnostics of that transpile target beside the module's own, as qvr check --target does (Interactive tools).

qvr run FILE [ENTRY [ARGUMENTS...]]

Execute one entry point of a checked module: a define computation or a program. With no entry name, or with --list, the command prints every entry point with its signature. A computation's signature gives its value parameters, static parameters, performed effects, and result type. A program's gives its data inputs, its result type, and the sample sites a run may condition on.

Each positional argument is a JSON literal and corresponds to one value parameter in declaration order. A computation runs under the configured runtime providers, validating the arguments and result against the specialized QIEC types with a fresh attachment table.

A program runs forward on the reference machine, the library's interpreter for QIEC. Its random instance replays the sites given with --site and draws and scores every other site, and its score instance accumulates. The run reports the program's value with the log joint density of the drawn and given sites, its observations, and its scores. A program's parameters may also be given by name with --data. Its extents are read from the data where the data fix them, so --static names only an extent that no data fixes, such as the object parameter of a program template (qvr run pooling.qvr school_effects 0.6 --static K=8). The run fixes a program's handlers, so --runtime applies to computations only.

Flags:

  • --list: print the file's entry points and exit.
  • --static NAME=TERM: specialize one static telescope binder with a closed type, index, or effect term. Repeat the flag once for every binder.
  • --data NAME=JSON: give one program parameter by name (a data input, an observation, an index map from rows to groups, or a scalar). Repeatable.
  • --site NAME=JSON: condition one sample site of a program on a value, drawing every other site. Repeatable. A site the run never reaches is an error.
  • --seed N: seed the reference generator a program run draws with, so two runs seeded alike draw alike.
  • --runtime FILE.json: select runtime providers and their options through a non-executable JSON configuration.
  • --fuel STEPS: bound the number of evaluation steps.
  • --exact: compute a computation's reals exactly, as rationals (NumberDomain.exact); the result prints as p/q, a float argument is read as the decimal it spells, and an operation the rationals are not closed under (exp, log, sqrt, sigmoid, ...) stops the run with an error naming it. A program draws and scores in floating point, so it takes no --exact.
  • --trace: write stable execution events to stderr in human-readable mode.
  • --json: emit the result, runtime label, and complete trace as JSON, with the entry's kind and a program's log joint. A failure instead emits a JSON diagnostic and exits 1.

For instance, this command specializes A to Int and passes the value argument 7:

qvr run identity.qvr identity 7 --static A=Int --json

and this one runs a program on four observations with its site a fixed:

qvr run calls.qvr prog '[0.1, 0.2, 0.3, 0.4]' --site a=0.5 --seed 0

The same invocation is available from Python through Program.run on a loaded module, from Compiler.entry and invoke_entry on its checked module, and from the REPL's :run, with the same validation, providers, trace, and diagnostic codes.

The default runtime configuration selects the built-in core provider. A configuration can select that provider with handler behavior or name an installed quivers.qiec_runtime entry point:

{
  "providers": [
    {
      "name": "core",
      "options": {
        "handlers": {
          "pass": {"kind": "passthrough"}
        }
      }
    }
  ]
}

The core provider accepts passthrough, scripted, and state handler configurations, the prelude kinds draw, draw-scoring, replay, score, and param, and the kind declared, which serves a foreign handler by the semantics its declaration states: a search, a collector, an enumeration, or a settlement, whose options on_failure and reports give its FailurePolicy and the list its report goes to. These options give the clause behavior, which lives only in the running Python process. The source handler still fixes the checked effect, coverage, forwarding policy, clause set, and resumption grades. Runtime plugins are discoverable by name but are loaded only when the configuration explicitly selects them.

Execution failures use stable codes including qiec-run-computation, qiec-run-config, qiec-run-arity, qiec-run-static, qiec-run-provider, qiec-run-validator, qiec-run-argument, qiec-run-evaluation, qiec-run-fuel, and qiec-run-result.

qvr test PATHS...

Run the test, property and example declarations of every module named: a .qvr file is one module, and a directory is a package of every module under it. Tests run on the reference machine, exactly over the rationals unless a test declares floating numbers. The command exits with 0 when every module loads and every test passes, and 1 otherwise.

Flags:

  • --json: print the machine-readable report of TestReport.to_data on stdout.
  • --match TEXT: run only the tests whose title contains TEXT.
  • --no-cache: run every test; by default a test whose content, code, and options are unchanged since it passed is reported from the cache.
  • --mutate: run each module's tests against every mutant of its rules, lexical entries, and constants (mutate_module), and report the mutants that survive; the exit status is 1 when any does.

No flag changes a test's tolerance, seed, case count, or number domain: those are pinned in the declaration.

qvr hash FILES...

Print the content identities of every .qvr file named (Content identity): the core hash of each checked declaration (families, effects, handlers, computations, entries, custom distribution families, instances, and index sorts), the module digest, the program digest a fit is keyed by, the hash of the exact bytes with the panproto commit of the grammar, and the alpha-normalized source hash of each top-level statement. Core hashes are invariant under renaming, reordering, comments, formatting, and every syntactic migration hop, and change with any change of meaning. The command exits with 0 when every file checks and 1 otherwise.

$ qvr hash regression.qvr
regression.qvr
  module   79817211fa3ef17cac97f50aa0a2ef473c16b43aeffd0910e70e838b26880d80
  program  9f2bd056504fbf74f50ad8401116b87bfdb8072ea9096a1aa488b6027f5bf1fd
  source   3ee5e80d4d71...  (grammar cc279318096d...)
  computation  42a0e13b1ef8...  model
  entry        3168dc6f65dc...  model
  ...

Flags:

  • --json: print one JSON record per file.
  • --normal-form KIND:NAME: print the canonical core form the declaration's hash digests, for one file (for example --normal-form computation:model), to see why two declarations hash apart.
  • --check-migrations [PATHS...]: instead of hashing, run the migration-invariance gate (check_migration_invariance) over the given files and directories, or over the corpus when none are given. Every hop of the migration chain, and every feature of the release hop on its own, is applied to each file that is valid source at the hop's revision, and the migrated file must have the file's own core hashes unless the hop declares itself semantic. The exit status is 1 on any failure.

qvr cache

Inspect and manage the project's persistent cache (ArtifactStore): checked modules and query results, fits (FitCache), and runs, each stored under the digest of everything that determines it. The cache lives in .qvr/cache at the project root (the nearest directory holding qvr.toml, .qvr, or .git), in $QVR_CACHE_DIR when that is set, or in the directory --dir PATH names; it is never placed in a temporary directory. Writing past its size limit (2 GiB unless set) evicts the least recently used entries, and every entry's payload is checked against its recorded digest when read.

Actions:

  • info: the directory, the limit, and the entries and bytes of each namespace.
  • list [--namespace NS]: every entry, most recently used first.
  • clear [--namespace NS]: delete entries.
  • prune [--max-size SIZE] [--older-than AGE]: evict entries unused for AGE, then the least recently used until the cache fits SIZE (its limit by default).
  • limit [SIZE]: show the limit, or set it and evict down to it.

Sizes take a K, M, or G suffix (powers of 1024) and ages an s, m, h, or d suffix. --json prints info and list as JSON.

qvr experiment

Run, hash, check, and export the experiments a module declares. Each action takes FILE:NAME (a .qvr or .qvr.md file, or a dotted module path below --root), where :NAME may be left out when the module declares one experiment. The command exits with 0 on success and 1 when anything is refused or a check fails; a refusal names its code and its clause's line and column (error[experiment-data-pin]: model.qvr:13:4: ...).

Actions:

  • run TARGET [--rerun] [--json] [--export DIR]: run every point of the experiment and store each record under its hash in the project's cache (namespace experiment); a point whose record is stored is read, not run, unless --rerun is given. --export DIR also writes a Workflow Run RO-Crate of the runs.
  • hash TARGET [--json]: print the experiment's hash, its program's content hash, and each point's hash, without running anything (plan_experiment).
  • check TARGET [--json] [--write-reference PATH]: compare the runs with the experiment's pinned reference within its pinned tolerances (check_experiment); with --write-reference, store the current results as the reference file PATH and print the reference clause that pins it.
  • export TARGET --to DIR: write a Workflow Run RO-Crate with a W3C PROV account of each run (write_crate).
  • list FILE: list the experiments a module declares with their entries and methods.

qvr weave DOCUMENTS...

Write the results of the experiments named by the {experiment} directives of each literate module, with their hashes (weave_document), running an experiment only when its records are not stored. --check writes nothing: it refuses a stale or unwoven result, a directive naming no experiment, and a prose reference naming no declaration, each as FILE:LINE:COLUMN: error[CODE]: ... (check_document). --rerun computes every run. The command exits with 0 when every document is woven or checks, and 1 otherwise.

qvr lsp

Run the Language Server over stdio, or pass --tcp PORT to bind a TCP port. --target TARGET enables live qiec:capability:* diagnostics for the selected transpiler. Editor extensions invoke this command over the Language Server Protocol. The server accepts later target changes through workspace/didChangeConfiguration, with either {"qvr": {"transpileTarget": "TARGET"}} or {"transpileTarget": "TARGET"}, and an empty target turns these diagnostics off (Interactive tools).

qvr transpile FILE

Transpile a .qvr file to a registered probabilistic programming backend. Use --to BACKEND for one target, --to-all for every registered target, or --list-targets to inspect the registry. The --output flag selects the destination of a run for one target, and --out-dir that of a run for several.

qvr kernel

Install or run the quivers Jupyter kernel. qvr kernel install registers the kernelspec. --user selects the user kernel directory, and --prefix PREFIX selects an explicit Jupyter prefix.

Module reference

The quivers.cli package exports the qvr entry point together with the tooling its subcommands share: checking of each file, the REPL session and its front ends, completion, and highlighting. quivers.cli.migrations exports the grammar migration chain, the language server is built by quivers.lsp, and the Jupyter kernel lives in quivers.kernel.

cli

Command-line entry points for quivers.

The main function is registered as the qvr console script in pyproject.toml.

Subcommands:

  • qvr check MODULES...: load, resolve, and compile every supplied .qvr file or dotted module path with the modules it imports, emitting structured diagnostics. Exits 0 on full success, non-zero when any module produces an error.
  • qvr migrate --from VER --to VER PATHS...: lower .qvr source files from one tagged grammar revision to another, via panproto migrations composed from the in-tree grammars/qvr/vcs chain.
  • qvr run MODULE[:ENTRY] [ENTRY] [ARGS...]: execute one checked QIEC computation or program of a file or a module path (qvr run pkg.experiments.boolean:fit) with JSON value arguments and an explicit runtime configuration.
  • qvr doc MODULES...: render each module's public interface.
  • qvr test PATHS...: run the test, property and example declarations of .qvr modules and packages; --mutate reports the mutants of a module's code that its tests do not reject.
  • qvr hash FILES...: print the content hash of every checked declaration, each statement's source hash, and the file's digests; --check-migrations checks that every syntactic migration hop preserves every core hash.
  • qvr cache {info,list,clear,prune,limit}: inspect and manage the project's persistent cache of checked modules, fits, and runs.

Output format: human-readable by default, structured JSON when --json is supplied. Each diagnostic carries:

  • file: source path,
  • line, col: 1-indexed source location,
  • severity: "error", "warning", or "note",
  • code: stable diagnostic code (parse, compile, effect_constraint, residuated_constraint),
  • message: human-readable description.

The Python surface beside main is the tooling the subcommands share: check_file and CheckDiagnostic for checking, and ReplSession with its completion, highlighting, and front-end helpers for driving a REPL session from Python. run_tui binds lazily because its Textual front end is an optional dependency.

SEMANTIC_TOKEN_MODIFIERS module-attribute

SEMANTIC_TOKEN_MODIFIERS: tuple[str, ...] = ('declaration', 'definition', 'deprecated')

The semantic token modifiers the language server advertises in its legend.

SEMANTIC_TOKEN_TYPES module-attribute

SEMANTIC_TOKEN_TYPES: tuple[str, ...] = ('comment', 'keyword', 'operator', 'punctuation', 'string', 'number', 'variable', 'type', 'function', 'namespace', 'decorator', 'error')

The semantic token types every QVR token reduces to. The order is significant: a token's index here is its type in the LSP semantic-token legend.

STYLE_TABLE module-attribute

STYLE_TABLE: dict[str, str] = {'comment': 'italic #5c6370', 'keyword': 'bold #c678dd', 'operator': '#56b6c2', 'punctuation': '#7f848e', 'string': '#98c379', 'number': '#d19a66', 'variable': '#abb2bf', 'type': 'bold #61afef', 'function': 'bold #e5c07b', 'namespace': 'bold #e06c75', 'decorator': '#c678dd', 'error': 'bold #e06c75 underline'}

Rich style strings keyed by semantic token type, shared by the TUI, the prompt_toolkit lexer, and the Jupyter kernel so that every front end colours a token alike.

CheckSeverity

CheckSeverity = Literal['error', 'warning', 'note']

The severity of a CheckDiagnostic.

CheckDiagnostic didactic-model

CheckDiagnostic(*, file: str, line: int, col: int, severity: CheckSeverity, code: str, message: str)

Bases: Model

One structured diagnostic that qvr check reports for a file.

PARAMETER DESCRIPTION
file

The path of the checked file.

TYPE: str

line

The 1-indexed source line, or 0 when the diagnostic has no position.

TYPE: int

col

The 1-indexed source column, or 0 when the diagnostic has no position.

TYPE: int

severity

"error", "warning", or "note".

TYPE: CheckSeverity

code

The stable diagnostic code, such as "parse" or "compile".

TYPE: str

message

The human-readable description.

TYPE: str

Completion didactic-model

Completion(*, text: str, kind: str, detail: str = '')

Bases: Model

One immutable completion candidate.

PARAMETER DESCRIPTION
text

Insertion text.

TYPE: str

kind

Candidate category, such as an environment name or command.

TYPE: str

detail

Short description shown with the candidate.

TYPE: str DEFAULT: ''

Span didactic-model

Span(*, start: int, end: int, token: str, text: str, line: int = 0, col: int = 0, end_line: int = 0, end_col: int = 0)

Bases: Model

One styled run of source.

PARAMETER DESCRIPTION
start

The run's start byte offset in the source.

TYPE: int

end

The run's end byte offset, exclusive.

TYPE: int

token

Its semantic token type, one of SEMANTIC_TOKEN_TYPES.

TYPE: str

text

The source text of the run.

TYPE: str

line

Its 0-indexed start line.

TYPE: int DEFAULT: 0

col

Its 0-indexed start column, in UTF-16 code units.

TYPE: int DEFAULT: 0

end_line

Its 0-indexed end line.

TYPE: int DEFAULT: 0

end_col

Its 0-indexed end column, in UTF-16 code units.

TYPE: int DEFAULT: 0

Diagnostic didactic-model

Diagnostic(*, message: str, severity: Severity, line: int = 0, col: int = 0, end_line: int = 0, end_col: int = 0, code: str = '')

Bases: Model

One structured diagnostic surfaced by the REPL or LSP.

ReplResponse didactic-model

ReplResponse(*, body: str = '', diagnostics: tuple[Diagnostic, ...] = (), body_kind: Literal['text', 'qvr', 'json', 'markdown'] = 'text')

Bases: Model

A single command's result, ready for any frontend to render.

body is the primary payload, which a frontend renders by pairing it with body_kind (text / qvr / json / markdown); each frontend is responsible for choosing the concrete renderer (Rich syntax block, prompt_toolkit ANSI, etc.) from body_kind. diagnostics carry structured errors and warnings.

ReplSession

ReplSession()

Stateful evaluator for a single REPL session.

Source code in src/quivers/cli/repl_session.py
def __init__(self) -> None:
    self._loaded_path: Path | None = None
    self._loaded_source: str = ""
    self._root_source_span: SourceSpan | None = None
    self._module: Module = Module(statements=())
    self._compiler: Compiler | None = None
    self._qiec_module: QiecModule | None = None
    self._qiec_registry: KernelRegistry | None = None
    self._generated_declarations: tuple[GeneratedDeclaration, ...] = ()
    self._env: dict[str, Any] = {}
    self._last_diags: tuple[Diagnostic, ...] = ()
    self._runtime = RuntimeConfiguration()
    self._runtime_source: str = "built-in core"
    self._last_run: ExecutionResult | None = None
    self._last_entry: EntryRun | None = None
    self._last_failure: ExecutionDiagnostic | None = None
    self.options = SessionOptions()
    # Track when the loaded file was last read so :reload can be
    # auto-fired on a modified mtime.
    self._loaded_mtime: float | None = None
    # Pinned `:watch EXPR` re-evaluations. The TUI renders these in
    # a dedicated panel; each install + reload re-runs every entry.
    self._watches: list[str] = []
    self._watch_results: dict[str, str] = {}

env property

env: dict[str, Any]

Live environment dict (every declared atom: objects, spaces, morphisms, rules, programs, deductions, signatures, encoders, decoders, losses, bundles, contractions).

last_entry property

last_entry: EntryRun | None

The most recent entry-point run of this session, or None.

last_failure property

last_failure: ExecutionDiagnostic | None

The diagnostic of the most recent failed run, or None once a run succeeds after it.

watch_results

watch_results() -> dict[str, str]

Return the current expr -> rendered map for pinned watches.

Source code in src/quivers/cli/repl_session.py
def watch_results(self) -> dict[str, str]:
    """Return the current ``expr -> rendered`` map for pinned watches."""
    return dict(self._watch_results)

env_kinds

env_kinds() -> dict[str, str]

Return a name -> semantic-token-type map for the live env.

Frontends pass this to the highlighter so an identifier renders in its env-known colour everywhere it appears, regardless of whether the surrounding grammar context parses cleanly.

Source code in src/quivers/cli/repl_session.py
def env_kinds(self) -> dict[str, str]:
    """Return a name -> semantic-token-type map for the live env.

    Frontends pass this to the highlighter so an identifier renders
    in its env-known colour everywhere it appears, regardless of
    whether the surrounding grammar context parses cleanly.
    """
    kinds: dict[str, str] = {}
    if self._compiler is not None:
        for name in self._compiler.objects:
            kinds[name] = "type"
        for name in self._compiler.spaces:
            kinds[name] = "type"
        for name in self._compiler.morphisms:
            kinds[name] = "function"
        for name in self._compiler.rules:
            kinds[name] = "namespace"
        for name in self._compiler.programs:
            kinds[name] = "function"
        for name in self._compiler.deductions:
            kinds[name] = "namespace"
        for name in self._compiler.syntaxes:
            kinds[name] = "type"
        for name in self._compiler.encoders:
            kinds[name] = "function"
        for name in self._compiler.decoders:
            kinds[name] = "function"
        for name in self._compiler.losses:
            kinds[name] = "function"
        for name in self._compiler.bundles:
            kinds[name] = "namespace"
        for name in self._compiler.contractions:
            kinds[name] = "function"
    kinds.update(
        qiec_env_kinds(self._module, generated=self._generated_declarations)
    )
    return kinds

dispatch

dispatch(line: str) -> ReplResponse

Route a raw input line to the right handler.

Source code in src/quivers/cli/repl_session.py
def dispatch(self, line: str) -> ReplResponse:
    """Route a raw input line to the right handler."""
    stripped = line.strip()
    if not stripped:
        return ReplResponse()
    if stripped.startswith(":"):
        cmd, _, rest = stripped[1:].partition(" ")
        return self._dispatch_meta(cmd, rest.strip())
    # Bare line: try statement first, then expression.
    return self._eval_source(stripped)

type_of

type_of(expr_source: str) -> ReplResponse

Print the type of a value-level expression.

Mirrors GHCi's :type: works on morphisms, programs, deductions, scoped sample / observe / let sites, and any expression that resolves to a morphism. For type-level names (objects, spaces, sorts), returns an error directing the user to :kind.

Source code in src/quivers/cli/repl_session.py
def type_of(self, expr_source: str) -> ReplResponse:
    """Print the type of a value-level expression.

    Mirrors GHCi's ``:type``: works on morphisms, programs,
    deductions, scoped sample / observe / let sites, and any
    expression that resolves to a morphism. For type-level names
    (objects, spaces, sorts), returns an error directing the user
    to ``:kind``.
    """
    if not self._compiler:
        return _err("no environment loaded; use :load <FILE> first")

    if SCOPE_SEPARATOR in expr_source:
        ref = resolve_scoped_path(self._compiler, expr_source.strip())
        if ref is None:
            return _err(f"unknown path: {expr_source}")
        if _ref_kind_class(ref.kind) == "type":
            return _err(
                f"{expr_source} is a type, not an expression; use :kind {expr_source}"
            )
        return _resp(self._type_signature_for_ref(ref), body_kind="qvr")

    bare = expr_source.strip()
    qiec = self._qiec_binding_map().get(bare)
    if qiec is not None:
        if qiec.kind in {"index", "family", "effect"}:
            return _err(f"{bare} is a type, not an expression; use :kind {bare}")
        signature = (
            self._qiec_signature(qiec)
            if qiec.kind == "index-map"
            else _render_qiec_binding_signature(qiec, bare)
        )
        return _resp(
            signature or f"{bare} :: {qiec.kind}",
            body_kind="qvr",
        )
    ambiguity = self._qiec_ambiguity(bare)
    if ambiguity is not None:
        return _err(ambiguity)
    if prelude_effect(bare) is not None:
        return _err(f"{bare} is a type, not an expression; use :kind {bare}")
    if "." in bare and all(part.isidentifier() for part in bare.split(".")):
        operation = qualified_operation_signature(self._module, bare)
        if operation is not None:
            return _resp(operation, body_kind="qvr")
        owner, _, member = bare.partition(".")
        return _err(
            f"unknown operation {member!r}: {owner!r} is neither an effect "
            "interface nor an instance declaring it"
        )
    if bare.isidentifier():
        line = self._value_line_for_name(bare)
        if line is not None:
            return _resp(line, body_kind="qvr")
        if self._is_type_level_name(bare):
            return _err(f"{bare} is a type, not an expression; use :kind {bare}")

    # Try to resolve as an expression (morphism reference / composition).
    # We drive the compiler's own ``_compile_expr`` inference rather
    # than re-running the full module compile: ``_compile_expr``
    # reads ``_morphisms`` / ``_objects`` / ``_spaces`` but does
    # not mutate them, so the session's already-compiled state is
    # the right environment to ask "what is the type of e?" in.
    try:
        mod = parse(f"export {expr_source}", file_path="<expr>")
    except ParseError as e:
        # If the user wrote a type expression like ``FinSet 3``,
        # parsing as an output binding fails; surface a hint.
        if self._parses_as_type(expr_source):
            return _err(
                f"{expr_source} is a type expression; use :kind {expr_source}"
            )
        return _err(f"parse error: {e}")
    expr_ast = _extract_export_expr(mod)
    if expr_ast is None:
        return _err("expression did not resolve to a morphism")
    try:
        morph = self._compiler._compile_expr(expr_ast)
    except CompileError as e:
        return _err(f"type error: {e}")
    if morph is None:
        return _err("expression did not resolve to a morphism")
    return _resp(
        self._type_signature_for_morphism(expr_source, morph),
        body_kind="qvr",
    )

transpile_module

transpile_module(target: str) -> ReplResponse

Emit the loaded module as source for the named transpile backend.

Mirrors the qvr transpile CLI subcommand, dispatched in-session against the currently-loaded Module. Returns the transpiled bytes decoded as UTF-8; never mutates session state.

Errors:

  • No module loaded yet (caller must run :load FILE first).
  • Empty or whitespace-only target string.
  • Target is not in available_targets.
  • The walker raises UnsupportedConstruct (the message carries the offending construct kinds).
Source code in src/quivers/cli/repl_session.py
def transpile_module(self, target: str) -> ReplResponse:
    """Emit the loaded module as source for the named transpile
    backend.

    Mirrors the ``qvr transpile`` CLI
    subcommand, dispatched in-session against the currently-loaded
    [`Module`][quivers.dsl.ast_nodes.Module]. Returns the
    transpiled bytes decoded as UTF-8; never mutates session state.

    Errors:

    - No module loaded yet (caller must run ``:load FILE`` first).
    - Empty or whitespace-only target string.
    - Target is not in
      [`available_targets`][quivers.transpile.available_targets].
    - The walker raises
      [`UnsupportedConstruct`][quivers.transpile.UnsupportedConstruct]
      (the message carries the offending construct kinds).
    """
    if self._compiler is None:
        return _err("no environment loaded; use :load <FILE> first")
    target = target.strip()
    if not target:
        return _err("usage: :transpile <TARGET>")

    targets = available_targets()
    if target not in targets:
        return _err(f"unknown target {target!r}; available: {', '.join(targets)}")
    try:
        output = transpile(self._module, target=target)
    except UnsupportedConstruct as e:
        return _err(str(e))
    return _resp(output.decode("utf-8"))

runtime

runtime(specification: str = '') -> ReplResponse

Show or replace the explicit runtime-provider configuration.

Source code in src/quivers/cli/repl_session.py
def runtime(self, specification: str = "") -> ReplResponse:
    """Show or replace the explicit runtime-provider configuration."""

    specification = specification.strip()
    if not specification:
        payload = self._runtime.to_data()
        payload["source"] = self._runtime_source
        return _resp(json.dumps(payload, indent=2), body_kind="json")
    path = Path(specification).expanduser()
    try:
        if path.exists():
            self._runtime = load_runtime_configuration(path)
            self._runtime_source = str(path)
        elif path.suffix.lower() == ".json" or "/" in specification:
            return _err(
                f"runtime configuration not found: {path}", code="qiec-run-config"
            )
        else:
            self._runtime = RuntimeConfiguration(
                selections=(RuntimeSelection(provider=specification),)
            )
            # Instantiate now so a misspelled provider fails at :runtime,
            # not after the next computation has been prepared.
            self._runtime.instantiate()
            self._runtime_source = f"provider {specification}"
    except (ExecutionFailure, ValueError) as error:
        if isinstance(error, ExecutionFailure):
            return _execution_error(error)
        return _err(str(error), code="qiec-run-config")
    self._last_run = None
    return _resp(f"runtime attached: {self._runtime.label}")

detach_runtime

detach_runtime() -> ReplResponse

Remove every runtime provider from this session.

Source code in src/quivers/cli/repl_session.py
def detach_runtime(self) -> ReplResponse:
    """Remove every runtime provider from this session."""

    previous = self._runtime.label
    self._runtime = RuntimeConfiguration(selections=())
    self._runtime_source = "detached"
    self._last_run = None
    return _resp(f"runtime detached: {previous}")

run_computation

run_computation(invocation: str) -> ReplResponse

Execute NAME [JSON ...] [--data NAME=JSON] [--site NAME=JSON] [--static NAME=TERM] [--fuel STEPS] [--seed N].

The entry is a define computation or a program, invoked through the same invoke_entry as qvr run, so its validation, providers, trace, and error codes are those of the command line. :run alone lists the module's entry points.

PARAMETER DESCRIPTION
invocation

The entry name and its arguments, as typed after :run.

TYPE: str

RETURNS DESCRIPTION
ReplResponse

The value, its type, the runtime label, the trace length, and a program's log joint; or the diagnostic of a failure.

Source code in src/quivers/cli/repl_session.py
def run_computation(self, invocation: str) -> ReplResponse:
    """Execute ``NAME [JSON ...] [--data NAME=JSON] [--site NAME=JSON]
    [--static NAME=TERM] [--fuel STEPS] [--seed N]``.

    The entry is a ``define`` computation or a ``program``, invoked
    through the same [`invoke_entry`][quivers.qiec.entries.invoke_entry]
    as ``qvr run``, so its validation, providers, trace, and error
    codes are those of the command line. ``:run`` alone lists the
    module's entry points.

    Parameters
    ----------
    invocation : str
        The entry name and its arguments, as typed after ``:run``.

    Returns
    -------
    ReplResponse
        The value, its type, the runtime label, the trace length,
        and a program's log joint; or the diagnostic of a failure.
    """

    if self._qiec_module is None:
        return _err(
            "no checked module loaded; use :load <FILE> first",
            code="qiec-run-module",
        )
    try:
        parts = shlex.split(invocation)
    except ValueError as error:
        return _err(f"invalid :run invocation: {error}", code="qiec-run-config")
    if not parts:
        lines = [render_entry(point) for point in entry_points(self._qiec_module)]
        return _resp("\n".join(lines) if lines else "(no entry points)")
    name = parts.pop(0)
    statics: list[str] = []
    data: list[str] = []
    sites: list[str] = []
    values: list[HostValue] = []
    fuel: int | None = None
    seed: int | None = None
    index = 0
    try:
        while index < len(parts):
            option, separator, inline = parts[index].partition("=")
            if option in ("--static", "--data", "--site", "--fuel", "--seed"):
                if separator:
                    text = inline
                else:
                    index += 1
                    if index >= len(parts):
                        raise ValueError(f"{option} requires a value")
                    text = parts[index]
                if option == "--static":
                    statics.append(text)
                elif option == "--data":
                    data.append(text)
                elif option == "--site":
                    sites.append(text)
                elif option == "--fuel":
                    fuel = _fuel(text)
                else:
                    seed = int(text)
            else:
                values.append(json_value(json.loads(parts[index])))
            index += 1
        run = invoke_entry(
            self._qiec_module,
            name,
            tuple(values),
            data=parse_bindings(data),
            sites=parse_bindings(sites),
            static_arguments=tuple(statics),
            runtime=self._runtime,
            fuel=fuel,
            seed=seed,
        )
    except json.JSONDecodeError as error:
        return _err(
            f"value arguments must be JSON: {error.msg}",
            code="qiec-run-config",
        )
    except (ValueError, KeyError) as error:
        self._last_failure = ExecutionDiagnostic(
            code="qiec-run-config", message=str(error), computation=name
        )
        return _err(str(error), code="qiec-run-config")
    except ExecutionFailure as error:
        self._last_failure = error.diagnostic
        return _execution_error(error)
    self._last_run = run.result
    self._last_entry = run
    self._last_failure = None
    payload = run.to_data()
    summary: dict[str, object] = {
        "kind": payload["kind"],
        "value": payload["value"],
        "type": payload["result_type"],
        "runtime": payload["runtime"],
        "trace_events": len(run.result.trace),
    }
    if "log_joint" in payload:
        summary["log_joint"] = payload["log_joint"]
    return _resp(json.dumps(summary, indent=2), body_kind="json")

kind_of

kind_of(expr_source: str) -> ReplResponse

Print the kind of a type-level name or type expression.

Mirrors GHCi's :kind: works on objects, spaces, sorts, atoms, constructors, and bare type expressions like FinSet 3 or A * B. For value-level names (morphisms, programs, sites), returns an error directing the user to :type.

Source code in src/quivers/cli/repl_session.py
def kind_of(self, expr_source: str) -> ReplResponse:
    """Print the kind of a type-level name or type expression.

    Mirrors GHCi's ``:kind``: works on objects, spaces, sorts,
    atoms, constructors, and bare type expressions like
    ``FinSet 3`` or ``A * B``. For value-level names (morphisms,
    programs, sites), returns an error directing the user to
    ``:type``.
    """
    if not self._compiler:
        return _err("no environment loaded; use :load <FILE> first")

    if SCOPE_SEPARATOR in expr_source:
        ref = resolve_scoped_path(self._compiler, expr_source.strip())
        if ref is None:
            return _err(f"unknown path: {expr_source}")
        if _ref_kind_class(ref.kind) == "value":
            return _err(
                f"{expr_source} is an expression, not a type; use :type {expr_source}"
            )
        return _resp(self._type_line_for_ref(ref), body_kind="qvr")

    bare = expr_source.strip()
    qiec = self._qiec_binding_map().get(bare)
    if qiec is not None:
        if qiec.kind in {"index", "family", "effect"}:
            return _resp(
                _render_qiec_binding_signature(qiec, bare)
                or f"{bare} :: {qiec.kind}",
                body_kind="qvr",
            )
        return _err(f"{bare} is an expression, not a type; use :type {bare}")
    ambiguity = self._qiec_ambiguity(bare)
    if ambiguity is not None:
        return _err(ambiguity)
    prelude = prelude_effect(bare)
    if prelude is not None:
        return _resp(render_effect(prelude).splitlines()[0], body_kind="qvr")
    if bare.isidentifier():
        line = self._type_line_for_name(bare)
        if line is not None:
            return _resp(line, body_kind="qvr")
        if self._is_value_level_name(bare):
            return _err(f"{bare} is an expression, not a type; use :type {bare}")

    # Type-expression form: resolve through the compiler's space
    # resolver and pretty-print as a QVR object declaration.
    try:
        mod = parse(f"object __probe__ : {expr_source}", file_path="<kind>")
    except ParseError as e:
        return _err(f"parse error: {e}")
    if (
        not mod.statements
        or not isinstance(mod.statements[0], ObjectDecl)
        or not isinstance(mod.statements[0].init, TypeFromExpr)
    ):
        return _err("expected a type expression")
    texpr: ObjectExpr = mod.statements[0].init.expr
    probe = self._scratch_compiler()
    try:
        obj = probe._resolve_any_space(texpr)
    except CompileError as e:
        return _err(f"kind error: {e}")
    except Exception as e:
        return _err(f"kind error: {e}")
    return _resp(
        f"{expr_source} :: {_pretty_object(obj)}",
        body_kind="qvr",
    )

plate

plate(name: str, *, fmt: str = 'table') -> ReplResponse

Render the plate diagram for name (a program).

fmt selects the output format: "table" (default, in-TUI Rich table; also has a plain-text fallback), "mermaid", "dot", "tikz", "daft", or "open" (render via daft or graphviz, save to a temp PNG, and open with the system default opener).

Source code in src/quivers/cli/repl_session.py
def plate(self, name: str, *, fmt: str = "table") -> ReplResponse:
    """Render the plate diagram for ``name`` (a program).

    ``fmt`` selects the output format: ``"table"`` (default,
    in-TUI Rich table; also has a plain-text fallback),
    ``"mermaid"``, ``"dot"``, ``"tikz"``, ``"daft"``, or
    ``"open"`` (render via daft or graphviz, save to a temp
    PNG, and open with the system default opener).
    """
    if self._compiler is None:
        return _err("no environment loaded; use :load <FILE> first")
    graph = build_plate_graph(self._compiler, name)
    if graph is None:
        return _err(f"no program named {name!r} in the loaded module")
    if fmt == "mermaid":
        return _resp(render_mermaid(graph), body_kind="markdown")
    if fmt == "dot":
        return _resp(render_dot(graph))
    if fmt == "tikz":
        return _resp(render_tikz(graph))
    if fmt == "daft":
        return _resp(render_daft(graph))
    if fmt == "open":
        return self._plate_open(graph)
    # Default: plain-text table (TUI also accepts this and
    # wraps it through the Rich highlighter for colour).
    return _resp(render_table_plain(graph))

graph

graph(name: str, *, fmt: str = 'table') -> ReplResponse

Render a step-flow view of name (a program).

The step-flow view lists the program's body steps one per row with their dependency parents on the side, plus an indented sub-block for any marginalize body. Same fmt flags as :plate.

Source code in src/quivers/cli/repl_session.py
def graph(self, name: str, *, fmt: str = "table") -> ReplResponse:
    """Render a step-flow view of ``name`` (a program).

    The step-flow view lists the program's body steps one per
    row with their dependency parents on the side, plus an
    indented sub-block for any marginalize body. Same ``fmt``
    flags as ``:plate``.
    """
    if self._compiler is None:
        return _err("no environment loaded; use :load <FILE> first")
    graph = build_plate_graph(self._compiler, name)
    if graph is None:
        return _err(f"no program named {name!r} in the loaded module")
    # The graph and plate diagrams share a model; ``:graph``
    # uses a step-oriented rendering vs ``:plate``'s
    # variable-oriented one.
    if fmt == "mermaid":
        return _resp(render_mermaid(graph), body_kind="markdown")
    if fmt == "dot":
        return _resp(render_dot(graph))
    if fmt == "open":
        return self._plate_open(graph)
    # The graph was built from this declaration, so it exists.
    lines = _scoped_step_lines(self._compiler.programs[name].draws, name)
    return _resp(_render_step_flow(graph, lines))

where

where(name: str) -> ReplResponse

List every scope path whose final segment is name.

Source code in src/quivers/cli/repl_session.py
def where(self, name: str) -> ReplResponse:
    """List every scope path whose final segment is ``name``."""
    if self._compiler is None:
        return _err("no environment loaded; use :load <FILE> first")
    refs = find_all_references(self._compiler, name)
    if not refs:
        return _err(f"no references to {name!r}")
    lines = [f"references to {name!r}:"]
    for ref in refs:
        lines.append(f"  {ref.kind:14} {ref.path}")
    return _resp("\n".join(lines))

effects

effects(name: str) -> ReplResponse

Compare declared and inferred effect sets for a program.

Source code in src/quivers/cli/repl_session.py
def effects(self, name: str) -> ReplResponse:
    """Compare declared and inferred effect sets for a program."""
    ambiguity = self._qiec_ambiguity(name)
    if ambiguity is not None:
        return _err(ambiguity)
    qiec = self._qiec_binding_map().get(name)
    if qiec is not None:
        declaration = qiec.declaration
        if isinstance(declaration, QiecEffectDecl):
            operations = ", ".join(op.name for op in declaration.operations)
            return _resp(
                f"effect {declaration.name}\n  operations: {{{operations}}}"
            )
        if isinstance(
            declaration,
            QiecInterpretationDecl
            | QiecRelationScoreDecl
            | QiecStringGraphScoreDecl,
        ):
            inferred = self._inferred_row(declaration.name)
            if inferred is not None:
                return _resp(
                    f"computation {declaration.name}\n  inferred  : {inferred}"
                )
        if isinstance(declaration, QiecComputationDecl):
            row = declaration.effects
            entries = ", ".join(entry.instance for entry in row.entries)
            tail = row.tail or "(closed)"
            lacks = ", ".join(row.lacks) or "(none)"
            lines = [
                f"computation {declaration.name}:",
                f"  instances : {{{entries}}}",
                f"  tail      : {tail}",
                f"  lacks     : {{{lacks}}}",
            ]
            inferred = self._inferred_row(declaration.name)
            if inferred is not None:
                lines.append(f"  inferred  : {inferred}")
            return _resp("\n".join(lines))
        if isinstance(declaration, QiecHandlerDecl):
            grades = ", ".join(
                f"{clause.operation}:{clause.grade}"
                for clause in declaration.clauses
            )
            return _resp(
                f"handler {declaration.name} for {declaration.effect.name}:\n"
                f"  coverage  : {declaration.coverage}\n"
                f"  forwards  : {declaration.forwards_unknown}\n"
                f"  resumptions: {{{grades}}}"
            )
        return _err(f"{name!r} does not declare an effect row")
    prelude = prelude_effect(name)
    if prelude is not None:
        operations = ", ".join(op.name for op in prelude.operations)
        return _resp(f"effect {name} (prelude)\n  operations: {{{operations}}}")

    if self._compiler is None:
        return _err("no environment loaded; use :load <FILE> first")
    graph = build_plate_graph(self._compiler, name)
    if graph is None:
        return _err(f"no program named {name!r} in the loaded module")
    declared = _declared_effects_for_program(self._compiler, name)
    inferred = _inferred_effects_from_graph(graph)
    lines = [
        f"program {name}:",
        f"  declared : {{{', '.join(sorted(declared)) or '(none)'}}}",
        f"  inferred : {{{', '.join(sorted(inferred))}}}",
    ]
    checked = self._inferred_row(name)
    if checked is not None:
        lines.append(f"  checked  : {checked}")
    leak = inferred - (declared or inferred)
    missing = declared - inferred if declared else set()
    if declared and leak:
        lines.append(
            f"  ! leak    : {{{', '.join(sorted(leak))}}}"
            " (body uses effects not declared)"
        )
    if declared and missing:
        lines.append(
            f"  ! unused  : {{{', '.join(sorted(missing))}}}"
            " (declared but not used)"
        )
    if not declared:
        lines.append("  (no [effects=[...]] declared)")
    return _resp("\n".join(lines))

shape

shape(name: str) -> ReplResponse

Render the ChainShape of the named program.

Source code in src/quivers/cli/repl_session.py
def shape(self, name: str) -> ReplResponse:
    """Render the ``ChainShape`` of the named program."""
    if self._compiler is None:
        return _err("no environment loaded; use :load <FILE> first")
    try:
        shape_obj = ChainShape.from_module(self._module)
    except Exception as exc:
        return _err(f"chain shape: {exc}")
    # ChainShape walks the module's first program decl
    # automatically; ``name`` is used only to disambiguate
    # output. Stay graceful when the module has multiple
    # programs and only one matches.
    steps = list(shape_obj.steps)
    if not steps:
        return _err(f"no program steps in module for {name!r}")
    lines = [
        f"chain shape ({shape_obj.algebra_name}):",
        "  #  depth  kind         name        size",
        "  -  -----  -----------  ----------  ----",
    ]
    for i, step in enumerate(steps, start=1):
        size = (
            str(step.intermediate_size)
            if step.intermediate_size is not None
            else "?"
        )
        lines.append(
            f"  {i:<3d} {step.depth:<5d}  {step.kind:<11s}  "
            f"{step.name:<10s}  {size:<4s}"
        )
    return _resp("\n".join(lines))

trace

trace(expr_source: str) -> ReplResponse

Step through elaboration of a morphism expression.

Source code in src/quivers/cli/repl_session.py
def trace(self, expr_source: str) -> ReplResponse:
    """Step through elaboration of a morphism expression."""
    if self._compiler is None:
        return _err("no environment loaded")
    try:
        mod = parse(f"export {expr_source}", file_path="<trace>")
    except ParseError as e:
        return _err(f"parse error: {e}")
    scratch = Compiler(_extend_module(self._module, mod.statements))
    # Re-run statement compilation so the env is fresh.
    try:
        scratch.compile()
    except (CompileError, QiecDiagnosticError) as e:
        return _err(f"compile error: {e}")
    # Walk the expression once and emit shape info as we go.
    lines: list[str] = []
    try:
        steps = _trace_expr(scratch, scratch._output_expr)
    except Exception as e:
        return _err(f"trace failed: {e}")
    for step in steps:
        lines.append(step)
    return _resp("\n".join(lines))

save

save(path: str = '') -> ReplResponse

Write the live module back to a .qvr file.

Source code in src/quivers/cli/repl_session.py
def save(self, path: str = "") -> ReplResponse:
    """Write the live module back to a ``.qvr`` file."""
    target = Path(path).expanduser() if path else self._loaded_path
    if target is None:
        return _err("usage: :save <FILE> (no file currently loaded)")
    try:
        source = module_to_source(self._module)
    except NotImplementedError as e:
        return _err(
            f"cannot emit: {e}. (the canonical emitter does not yet "
            "support every statement variant; edit the source file "
            "directly instead)"
        )
    try:
        target.write_text(source, encoding="utf-8")
    except OSError as e:
        return _err(f"write failed: {e}")
    return _resp(f"saved {target}")

watch

watch(expr: str) -> ReplResponse

Pin an expression for re-evaluation on every recompile.

Source code in src/quivers/cli/repl_session.py
def watch(self, expr: str) -> ReplResponse:
    """Pin an expression for re-evaluation on every recompile."""
    expr = expr.strip()
    if not expr:
        return _err("usage: :watch <EXPR>")
    if expr not in self._watches:
        self._watches.append(expr)
    self._refresh_watches()
    rendered = self._watch_results.get(expr, "(unresolved)")
    return _resp(f"watch {expr} => {rendered}", body_kind="qvr")

unwatch

unwatch(expr: str) -> ReplResponse

Remove a previously-pinned watch expression.

Source code in src/quivers/cli/repl_session.py
def unwatch(self, expr: str) -> ReplResponse:
    """Remove a previously-pinned watch expression."""
    expr = expr.strip()
    if not expr:
        # No argument: clear every watch.
        self._watches.clear()
        self._watch_results.clear()
        return _resp("cleared all watches")
    if expr not in self._watches:
        return _err(f"not watching: {expr}")
    self._watches.remove(expr)
    self._watch_results.pop(expr, None)
    return _resp(f"unwatched {expr}")

autoreload_if_stale

autoreload_if_stale() -> ReplResponse | None

Re-run :reload if the loaded file's mtime advanced.

Source code in src/quivers/cli/repl_session.py
def autoreload_if_stale(self) -> ReplResponse | None:
    """Re-run :reload if the loaded file's mtime advanced."""
    if not self.options.autoload_on_save:
        return None
    if self._loaded_path is None or self._loaded_mtime is None:
        return None
    try:
        current = self._loaded_path.stat().st_mtime
    except OSError:
        return None
    if current > self._loaded_mtime:
        return self.reload()
    return None

SessionOptions didactic-model

SessionOptions(*, highlight: bool = True, unicode: bool = True, show_axes: bool = True, paranoid: bool = False, autoload_on_save: bool = True, theme: str = 'ansi_dark', target: str = '')

Bases: Model

User-tunable knobs exposed via :set.

theme selects a Rich syntax theme for QVR bodies rendered via :info / :dump etc. Common values: ansi_dark, ansi_light, monokai, nord, solarized-dark, solarized-light, github-dark.

target class-attribute instance-attribute

target: str = ''

A transpile target whose capability diagnostics :load and :reload report beside the checked module's own, as qvr check --target does; empty for none.

check_file

check_file(path: Path | str, *, target: str | None = None, roots: tuple[Path, ...] | None = None) -> list[CheckDiagnostic]

Parse, resolve, constraint-check, and compile one module and its imports.

This is the per-file pipeline behind qvr check. It reports failures as diagnostics rather than raising, so an unreadable file yields an io diagnostic and a syntax error a parse one.

PARAMETER DESCRIPTION
path

The .qvr file to check, or a dotted module path below roots.

TYPE: Path | str

target

A transpile target whose missing capabilities are also reported, as qvr check --target does; None for none.

TYPE: str or None DEFAULT: None

roots

The directories module paths are relative to; for a file, its own directory when omitted, and for a module path the working directory.

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

RETURNS DESCRIPTION
list[CheckDiagnostic]

Every diagnostic the file produces, empty when it checks cleanly.

Source code in src/quivers/cli/check.py
def check_file(
    path: Path | str,
    *,
    target: str | None = None,
    roots: tuple[Path, ...] | None = None,
) -> list[CheckDiagnostic]:
    """Parse, resolve, constraint-check, and compile one module and its imports.

    This is the per-file pipeline behind ``qvr check``. It reports
    failures as diagnostics rather than raising, so an unreadable file
    yields an ``io`` diagnostic and a syntax error a ``parse`` one.

    Parameters
    ----------
    path : Path | str
        The ``.qvr`` file to check, or a dotted module path below
        ``roots``.
    target : str or None
        A transpile target whose missing capabilities are also
        reported, as ``qvr check --target`` does; ``None`` for none.
    roots : tuple[Path, ...] | None
        The directories module paths are relative to; for a file, its
        own directory when omitted, and for a module path the working
        directory.

    Returns
    -------
    list[CheckDiagnostic]
        Every diagnostic the file produces, empty when it checks
        cleanly.
    """
    program = parse_target(str(path))
    diags: list[CheckDiagnostic] = []
    try:
        flat = interpret_target(program, roots)
    except (OSError, ValueError) as e:
        return [
            CheckDiagnostic(
                file=str(path),
                line=0,
                col=0,
                severity="error",
                code="io",
                message=f"could not read file: {e}",
            )
        ]
    except ParseError as e:
        match = _PARSE_POSITION.search(str(e))
        line = int(match.group(1)) if match is not None else 0
        col = int(match.group(2)) if match is not None else 0
        diags.append(
            CheckDiagnostic(
                file=str(path),
                line=line,
                col=col,
                severity="error",
                code="parse",
                message=str(e),
            )
        )
        return diags
    except ModuleError as e:
        location = e.diagnostic.location
        suggestions = e.diagnostic.suggestions
        hint = (
            "; did you mean " + " or ".join(repr(name) for name in suggestions) + "?"
            if suggestions
            else ""
        )
        return [
            CheckDiagnostic(
                file=location.file,
                line=location.line,
                col=location.column,
                severity="error",
                code=e.code,
                message=e.diagnostic.message + hint,
            )
        ]
    try:
        check_module_language(
            flat, module_name=qiec_module_name(path), file_path=str(path)
        )
    except ModuleError as e:
        location = e.diagnostic.location
        return [
            CheckDiagnostic(
                file=location.file,
                line=location.line,
                col=location.column,
                severity="error",
                code=e.code,
                message=e.diagnostic.message,
            )
        ]
    except (CompileError, QiecDiagnosticError) as e:
        line = e.line
        col = e.column if isinstance(e, QiecDiagnosticError) else e.col
        return [
            _located(
                flat,
                CheckDiagnostic(
                    file=str(path),
                    line=line,
                    col=col,
                    severity="error",
                    code="compile" if isinstance(e, CompileError) else e.code,
                    message=str(e),
                ),
            )
        ]
    module = flat.module

    compiler_module = non_qiec_projection(module)
    # Constraint solver runs before compile so users see structural
    # diagnostics even when compilation would also fail.
    diags.extend(
        CheckDiagnostic(
            file=str(path),
            line=v.line,
            col=v.col,
            severity=_normalize_severity(v.severity),
            code=v.code,
            message=v.message,
        )
        for v in check_constraints(compiler_module)
    )

    # Family argument-shape pass: arity and elementwise compatibility
    # against the distribution's `arg_constraints`. Surfaces the
    # ``implicit-family-defaults`` warning and ``family-arg-shape``
    # errors / warnings.
    family_diags = [
        CheckDiagnostic(
            file=str(path),
            line=v.line,
            col=v.col,
            severity=_normalize_severity(v.severity),
            code=v.code,
            message=v.message,
        )
        for v in validate_family_arg_shapes(compiler_module)
    ]
    diags.extend(family_diags)
    has_family_shape_error = any(
        d.code == "family-arg-shape" and d.severity == "error" for d in family_diags
    )
    analysis = analyze_module(
        module,
        module_name=qiec_module_name(path),
        file_path=str(path),
        compile_categorical=not has_family_shape_error,
    )
    diags[:0] = [
        CheckDiagnostic(
            file=str(path),
            line=diagnostic.line,
            col=diagnostic.col,
            severity="error",
            code=diagnostic.code,
            message=diagnostic.message,
        )
        for diagnostic in analysis.qiec_diagnostics
    ]
    if has_family_shape_error:
        # Skip compile: the wider compiler would crash on shape-mismatched
        # args before we get a useful diagnostic.
        return diags

    if analysis.compile_error is not None:
        error = analysis.compile_error
        diags.append(
            CheckDiagnostic(
                file=str(path),
                line=getattr(error, "line", 0),
                col=getattr(error, "col", 0),
                severity="error",
                code="compile",
                message=str(error),
            )
        )

    if analysis.qiec_module is not None:
        diags.extend(hole_notes(analysis.qiec_module, module, str(path)))
    diags.extend(_generic_hole_notes(flat, path, diags))
    if analysis.compile_error is None:
        diags.extend(
            CheckDiagnostic(
                file=str(path),
                line=verdict.line,
                col=verdict.col,
                severity="note",
                code="deduction-extension",
                message=(
                    f"deduction {verdict.deduction} extends {verdict.signature}: "
                    f"{verdict.classification}, since {verdict.reason}; results of "
                    f"generic code over {verdict.signature} hold for "
                    f"{verdict.signature} only"
                ),
            )
            for verdict in extension_notes(module)
        )

    if target is not None and analysis.qiec_module is not None:
        diags.extend(
            CheckDiagnostic(
                file=str(path),
                line=diagnostic.line,
                col=diagnostic.col,
                severity="error",
                code=diagnostic.code,
                message=diagnostic.message,
            )
            for diagnostic in target_diagnostics(analysis.qiec_module, module, target)
        )

    return [_located(flat, diagnostic) for diagnostic in diags]

hole_notes

hole_notes(qiec_module: QiecModule, module: Module, file: str) -> list[CheckDiagnostic]

Report every typed hole of a checked module as a goal.

A module with holes checks; what its author needs back is each hole's goal type and the bindings in scope there, which these notes carry.

PARAMETER DESCRIPTION
qiec_module

The checked module.

TYPE: QiecModule

module

The parsed source, which locates type holes.

TYPE: Module

file

The checked file, named in each note.

TYPE: str

RETURNS DESCRIPTION
list[CheckDiagnostic]

One qiec-hole note per type hole and per value hole occurrence.

Source code in src/quivers/cli/check.py
def hole_notes(
    qiec_module: QiecModule, module: Module, file: str
) -> list[CheckDiagnostic]:
    """Report every typed hole of a checked module as a goal.

    A module with holes checks; what its author needs back is each hole's
    goal type and the bindings in scope there, which these notes carry.

    Parameters
    ----------
    qiec_module : QiecModule
        The checked module.
    module : Module
        The parsed source, which locates type holes.
    file : str
        The checked file, named in each note.

    Returns
    -------
    list[CheckDiagnostic]
        One ``qiec-hole`` note per type hole and per value hole occurrence.
    """
    notes: list[CheckDiagnostic] = []
    written = [
        hole
        for hole in surface_holes(module.statements)
        if isinstance(hole, QiecTypeHole)
    ]
    for name in type_hole_names(qiec_module):
        local = split_module(name)[1]
        site = next(
            (hole for hole in written if split_module(hole.name)[1] == local), None
        )
        notes.append(
            CheckDiagnostic(
                file=file,
                line=site.line if site is not None else 0,
                col=site.col if site is not None else 0,
                severity="note",
                code="qiec-hole",
                message=f"type hole ?{name} : Type",
            )
        )
    for goal in hole_goals(qiec_module):
        notes.append(
            CheckDiagnostic(
                file=file,
                line=goal.origin.line or 0,
                col=goal.origin.column or 0,
                severity="note",
                code="qiec-hole",
                message=f"goal {goal.render()} in {goal.declaration}",
            )
        )
    return notes

all_completions

all_completions(session: ReplSession, prefix: str) -> list[Completion]

Return every candidate whose text starts with prefix.

The caller (prompt_toolkit Completer, LSP completion handler) decides which slice to show.

PARAMETER DESCRIPTION
session

The session whose environment supplies name completions.

TYPE: ReplSession

prefix

The text typed so far.

TYPE: str

RETURNS DESCRIPTION
list[Completion]

Meta-command, transpile-target, environment, keyword, observation-option, and path candidates, in that order.

Source code in src/quivers/cli/repl_complete.py
def all_completions(session: ReplSession, prefix: str) -> list[Completion]:
    """Return every candidate whose text starts with ``prefix``.

    The caller (prompt_toolkit Completer, LSP completion handler)
    decides which slice to show.

    Parameters
    ----------
    session : ReplSession
        The session whose environment supplies name completions.
    prefix : str
        The text typed so far.

    Returns
    -------
    list[Completion]
        Meta-command, transpile-target, environment, keyword, observation-option,
        and path candidates, in that order.
    """
    out: list[Completion] = []
    out.extend(_meta_completions(prefix))
    out.extend(_transpile_target_completions(prefix))
    out.extend(_env_completions(session, prefix))
    out.extend(_keyword_completions(prefix))
    out.extend(
        Completion(
            text=name + "=", kind="option", detail=f"observation {field}: {carrier}"
        )
        for name, (field, carrier) in EVENT_OPTIONS.items()
        if prefix and name.startswith(prefix)
    )
    out.extend(_path_completions(prefix))
    return out

public_meta_commands

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

Return one public spelling for every registered meta-command.

The dispatch table registers each long spelling before its short aliases. Keeping the first name for each handler thus makes completion and the TUI palette follow the executable command surface without advertising aliases.

RETURNS DESCRIPTION
tuple[str, ...]

The long spelling of each meta-command, in registration order.

Source code in src/quivers/cli/repl_complete.py
def public_meta_commands() -> tuple[str, ...]:
    """Return one public spelling for every registered meta-command.

    The dispatch table registers each long spelling before its short aliases.
    Keeping the first name for each handler thus makes completion and the TUI
    palette follow the executable command surface without advertising aliases.

    Returns
    -------
    tuple[str, ...]
        The long spelling of each meta-command, in registration order.
    """
    seen: set[object] = set()
    commands: list[str] = []
    for name, handler in repl_session._META_COMMANDS.items():  # noqa: SLF001
        if handler in seen:
            continue
        seen.add(handler)
        commands.append(name)
    return tuple(commands)

to_pygments_pairs

to_pygments_pairs(source: str) -> list[tuple[_TokenType, str]]

Build (Pygments token, text) pairs suitable for prompt_toolkit.

prompt_toolkit's PygmentsLexer wraps a Pygments Lexer that yields (index, token, text); here we deliver the simpler (token, text) form directly used by prompt_toolkit.formatted_text.

PARAMETER DESCRIPTION
source

The QVR source to highlight.

TYPE: str

RETURNS DESCRIPTION
list[tuple[_TokenType, str]]

One pair per span, in source order.

Source code in src/quivers/cli/repl_highlight.py
def to_pygments_pairs(source: str) -> list[tuple[_TokenType, str]]:
    """Build ``(Pygments token, text)`` pairs suitable for prompt_toolkit.

    prompt_toolkit's PygmentsLexer wraps a Pygments Lexer that yields
    ``(index, token, text)``; here we deliver the simpler ``(token,
    text)`` form directly used by ``prompt_toolkit.formatted_text``.

    Parameters
    ----------
    source : str
        The QVR source to highlight.

    Returns
    -------
    list[tuple[pygments.token._TokenType, str]]
        One pair per span, in source order.
    """
    mapping = {
        "comment": Comment,
        "keyword": Keyword,
        "operator": Operator,
        "punctuation": Punctuation,
        "string": String,
        "number": Number,
        "variable": Name.Variable,
        "type": Name.Class,
        "function": Name.Builtin,
        "namespace": String.Symbol,
        "decorator": Name.Decorator,
        "error": PygmentsText,
    }
    out: list[tuple[_TokenType, str]] = []
    for span in tokenize(source):
        out.append((mapping.get(span.token, PygmentsText), span.text))
    return out

to_rich_text

to_rich_text(source: str, *, env_kinds: dict[str, str] | None = None, link_action: str | None = None) -> Text

Build a rich.text.Text from the highlighted source.

If link_action is set (e.g. "info"), identifiers that the grammar or env classified as something meaningful (type / function / namespace / variable when the name is in env_kinds) are wrapped as Rich console links pointing to "<link_action>:<name>". The TUI's RichLog on_click translator then runs :link_action <name> when the user clicks.

PARAMETER DESCRIPTION
source

The QVR source to highlight.

TYPE: str

env_kinds

Semantic kinds of names bound in the environment, as for tokenize.

TYPE: dict[str, str] or None DEFAULT: None

link_action

The meta-command clickable identifiers run, or None for no links.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
Text

The styled text.

RAISES DESCRIPTION
ModuleNotFoundError

If the optional Rich dependency is absent.

Source code in src/quivers/cli/repl_highlight.py
def to_rich_text(
    source: str,
    *,
    env_kinds: dict[str, str] | None = None,
    link_action: str | None = None,
) -> Text:
    """Build a `rich.text.Text` from the highlighted source.

    If ``link_action`` is set (e.g. ``"info"``), identifiers that the
    grammar or env classified as something meaningful (type / function
    / namespace / variable when the name is in env_kinds) are wrapped
    as Rich console links pointing to ``"<link_action>:<name>"``. The
    TUI's RichLog ``on_click`` translator then runs ``:link_action
    <name>`` when the user clicks.

    Parameters
    ----------
    source : str
        The QVR source to highlight.
    env_kinds : dict[str, str] or None
        Semantic kinds of names bound in the environment, as for
        `tokenize`.
    link_action : str or None
        The meta-command clickable identifiers run, or ``None`` for no
        links.

    Returns
    -------
    rich.text.Text
        The styled text.

    Raises
    ------
    ModuleNotFoundError
        If the optional Rich dependency is absent.
    """
    if not _RICH_AVAILABLE:
        raise ModuleNotFoundError(
            "Rich syntax highlighting requires quivers[repl]", name="rich"
        )
    out = Text()
    interesting = {"type", "function", "namespace"}
    for span in tokenize(source, env_kinds=env_kinds):
        style_str = STYLE_TABLE.get(span.token, "")
        if (
            link_action
            and span.token in interesting
            and span.text.replace("_", "").isalnum()
            and not span.text[0].isdigit()
        ):
            style = Style.parse(style_str) + Style(
                meta={"@click": f"{link_action}('{span.text}')"}
            )
            out.append(span.text, style=style)
        else:
            out.append(span.text, style=style_str)
    return out

to_semantic_token_data

to_semantic_token_data(source: str, *, env_kinds: dict[str, str] | None = None) -> list[int]

Encode source as the LSP SemanticTokens 5-tuple stream.

The stream is delta-encoded as [deltaLine, deltaStart, length, tokenType, tokenModifiers] per LSP 3.17. See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_semanticTokens for the encoding rules.

PARAMETER DESCRIPTION
source

The QVR source to encode.

TYPE: str

env_kinds

Semantic kinds of names bound in the environment, as for tokenize.

TYPE: dict[str, str] or None DEFAULT: None

RETURNS DESCRIPTION
list[int]

Five integers per token.

Source code in src/quivers/cli/repl_highlight.py
def to_semantic_token_data(
    source: str, *, env_kinds: dict[str, str] | None = None
) -> list[int]:
    """Encode ``source`` as the LSP SemanticTokens 5-tuple stream.

    The stream is delta-encoded as ``[deltaLine, deltaStart, length,
    tokenType, tokenModifiers]`` per LSP 3.17. See
    https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_semanticTokens
    for the encoding rules.

    Parameters
    ----------
    source : str
        The QVR source to encode.
    env_kinds : dict[str, str] or None
        Semantic kinds of names bound in the environment, as for
        `tokenize`.

    Returns
    -------
    list[int]
        Five integers per token.
    """
    type_index = {name: i for i, name in enumerate(SEMANTIC_TOKEN_TYPES)}
    out: list[int] = []
    prev_line = 0
    prev_col = 0
    for span in tokenize(source, env_kinds=env_kinds):
        if span.token in ("variable",) and not span.text.strip():
            # Pure whitespace at the start of the buffer; skip.
            continue
        if span.line != prev_line:
            prev_col = 0
        delta_line = span.line - prev_line
        delta_col = span.col - prev_col
        # Tokens that cross a newline aren't supported by the protocol;
        # split conservatively at the next newline.
        text = span.text
        length = _utf16_length(text)
        if "\n" in text:
            first_segment = text.split("\n", 1)[0]
            length = _utf16_length(first_segment)
        out.extend(
            [
                delta_line,
                delta_col,
                length,
                type_index.get(span.token, type_index["variable"]),
                0,
            ]
        )
        prev_line = span.line
        prev_col = span.col
    return out

to_semantic_token_legend

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

Return the semantic-token legend the language server advertises.

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

SEMANTIC_TOKEN_TYPES and SEMANTIC_TOKEN_MODIFIERS.

Source code in src/quivers/cli/repl_highlight.py
def to_semantic_token_legend() -> tuple[tuple[str, ...], tuple[str, ...]]:
    """Return the semantic-token legend the language server advertises.

    Returns
    -------
    tuple[tuple[str, ...], tuple[str, ...]]
        `SEMANTIC_TOKEN_TYPES` and `SEMANTIC_TOKEN_MODIFIERS`.
    """
    return SEMANTIC_TOKEN_TYPES, SEMANTIC_TOKEN_MODIFIERS

tokenize

tokenize(source: str | bytes, *, env_kinds: dict[str, str] | None = None) -> list[Span]

Return the styled span list for source.

PARAMETER DESCRIPTION
source

The QVR source to highlight.

TYPE: str or bytes

env_kinds

Semantic kinds of names bound in the environment, as described below; None highlights from the grammar alone.

TYPE: dict[str, str] or None DEFAULT: None

RETURNS DESCRIPTION
list[Span]

The source's spans in order, each tagged with a semantic token type.

Drives directly on the tree-sitter parse so that anonymous tokens
(keywords, punctuation) are preserved; panproto's Schema view
strips those, so we go to tree-sitter for highlighting and keep
panproto for parsing into the didactic AST.
``env_kinds`` enables semantic highlighting: a mapping from name
to one of ``"type"``, ``"function"``, ``"namespace"`` (or any
SEMANTIC_TOKEN_TYPES value). Identifiers the grammar leaves as
``"variable"`` are upgraded to their env-known kind, so a name
looks the same across the input pane, ``:type``, ``:info``, and
any other surface, regardless of whether the surrounding context
parses as a valid declaration.
Failure path: if the parser raises, the entire source is returned
as a single ``error`` span. Callers can downgrade to a no-highlight
render but the buffer still displays.
Source code in src/quivers/cli/repl_highlight.py
def tokenize(
    source: str | bytes,
    *,
    env_kinds: dict[str, str] | None = None,
) -> list[Span]:
    """Return the styled span list for ``source``.

    Parameters
    ----------
    source : str or bytes
        The QVR source to highlight.
    env_kinds : dict[str, str] or None
        Semantic kinds of names bound in the environment, as described
        below; ``None`` highlights from the grammar alone.

    Returns
    -------
    list[Span]
        The source's spans in order, each tagged with a semantic token
        type.

    Drives directly on the tree-sitter parse so that anonymous tokens
    (keywords, punctuation) are preserved; panproto's Schema view
    strips those, so we go to tree-sitter for highlighting and keep
    panproto for parsing into the didactic AST.

    ``env_kinds`` enables semantic highlighting: a mapping from name
    to one of ``"type"``, ``"function"``, ``"namespace"`` (or any
    SEMANTIC_TOKEN_TYPES value). Identifiers the grammar leaves as
    ``"variable"`` are upgraded to their env-known kind, so a name
    looks the same across the input pane, ``:type``, ``:info``, and
    any other surface, regardless of whether the surrounding context
    parses as a valid declaration.

    Failure path: if the parser raises, the entire source is returned
    as a single ``error`` span. Callers can downgrade to a no-highlight
    render but the buffer still displays.
    """
    if isinstance(source, str):
        src_bytes = source.encode("utf-8")
    else:
        src_bytes = source
    if not src_bytes:
        return []
    try:
        parser, _, _ = _load_parser()
        tree = parser.parse(src_bytes)
    except Exception:
        return [
            Span(
                start=0,
                end=len(src_bytes),
                token="error",
                text=src_bytes.decode("utf-8", errors="replace"),
                line=0,
                col=0,
                end_line=src_bytes.count(b"\n"),
                end_col=0,
            )
        ]

    leaves: list[tuple[tree_sitter.Node, str | None, str | None]] = []

    def walk(
        node: tree_sitter.Node,
        parent_kind: str | None,
        field_name: str | None,
    ) -> None:
        """Collect leaf nodes with their enclosing grammar context.

        Parameters
        ----------
        node : tree_sitter.Node
            The current syntax node.
        parent_kind : str or None
            Its enclosing node's grammar kind.
        field_name : str or None
            Its field in the enclosing node.
        """
        if not node.children:
            leaves.append((node, parent_kind, field_name))
            return
        for index, child in enumerate(node.children):
            walk(child, node.type, node.field_name_for_child(index))

    walk(tree.root_node, None, None)

    spans: list[Span] = []
    cursor = 0
    for leaf, parent_kind, field_name in leaves:
        sb = leaf.start_byte
        eb = leaf.end_byte
        if sb > cursor:
            gap = src_bytes[cursor:sb].decode("utf-8", errors="replace")
            spans.append(
                _position(
                    Span(start=cursor, end=sb, token="variable", text=gap),
                    src_bytes,
                )
            )
        text = src_bytes[sb:eb].decode("utf-8", errors="replace")
        parts = _contextual_token_parts(leaf, text, parent_kind, field_name)
        if parts:
            start = sb
            for style, part in parts:
                end = start + len(part.encode("utf-8"))
                spans.append(
                    _position(
                        Span(
                            start=start, end=end, token=_style_class(style), text=part
                        ),
                        src_bytes,
                    )
                )
                start = end
            cursor = eb
            continue
        token = _classify(leaf.type, text, parent_kind, field_name)
        # Semantic upgrade: if the grammar produced a generic
        # "variable" classification but the env knows this name as a
        # type/function/namespace, paint it the env colour. This is
        # the seam that gives consistent highlighting across all REPL
        # output surfaces.
        if env_kinds and token == "variable":
            env_kind = env_kinds.get(text)
            if env_kind:
                token = env_kind
        spans.append(
            _position(Span(start=sb, end=eb, token=token, text=text), src_bytes)
        )
        cursor = eb
    if cursor < len(src_bytes):
        tail = src_bytes[cursor:].decode("utf-8", errors="replace")
        spans.append(
            _position(
                Span(
                    start=cursor,
                    end=len(src_bytes),
                    token="variable",
                    text=tail,
                ),
                src_bytes,
            )
        )
    return _merge_split_operators(spans, src_bytes)

run_plain

run_plain(session: ReplSession) -> int

Run the single-line REPL front end on session.

The front end reads with prompt_toolkit when it is installed and with bare standard input otherwise.

PARAMETER DESCRIPTION
session

The session that evaluates each line.

TYPE: ReplSession

RETURNS DESCRIPTION
int

The process exit status, 0 when the user quits.

Source code in src/quivers/cli/repl_prompt.py
def run_plain(session: ReplSession) -> int:
    """Run the single-line REPL front end on ``session``.

    The front end reads with prompt_toolkit when it is installed and
    with bare standard input otherwise.

    Parameters
    ----------
    session : ReplSession
        The session that evaluates each line.

    Returns
    -------
    int
        The process exit status, ``0`` when the user quits.
    """
    getline: Callable[[], str | None] = _bare_input
    if _PROMPT_AVAILABLE:
        history_path = _history_path()
        history_path.parent.mkdir(parents=True, exist_ok=True)

        class _Completer(Completer):
            def get_completions(
                self, document: Document, complete_event: CompleteEvent
            ) -> Iterable[Completion]:
                """Yield completions at the current source position.

                Parameters
                ----------
                document : Document
                    The editable input buffer.
                complete_event : CompleteEvent
                    The completion request.

                Returns
                -------
                Iterable[Completion]
                    Matching names with their replacement positions.
                """
                del complete_event
                word = _completion_prefix(document.text, document.cursor_position)
                for c in all_completions(session, word):
                    yield Completion(
                        text=c.text,
                        start_position=-len(word),
                        display_meta=c.detail,
                    )

        ps: PromptSession[str] = PromptSession(
            message="qvr> ",
            history=FileHistory(str(history_path)),
            completer=_Completer(),
            lexer=PygmentsLexer(QvrLexer),
            multiline=False,
        )

        getline = ps.prompt

    while True:
        try:
            line = getline()
        except EOFError, KeyboardInterrupt:
            sys.stdout.write("\n")
            return 0
        if line is None:
            return 0
        # Allow `:reload` to auto-fire if file changed on disk.
        auto = session.autoreload_if_stale()
        if auto is not None:
            _render(auto)
        response = session.dispatch(line)
        if response.body == "__quit__":
            return 0
        _render(response)

render_qiec_signature

render_qiec_signature(module: Module, name: str) -> str | None

Return a compact source signature for one QIEC binding.

This works from the authored AST rather than a backend compiler object, so it remains available when a document contains only indexed families or effect interfaces.

PARAMETER DESCRIPTION
module

The parsed module holding the binding.

TYPE: Module

name

The QIEC binding to describe.

TYPE: str

RETURNS DESCRIPTION
str or None

The compact signature, or None when name is not a QIEC binding of module.

Source code in src/quivers/cli/repl_session.py
def render_qiec_signature(module: Module, name: str) -> str | None:
    """Return a compact source signature for one QIEC binding.

    This works from the authored AST rather than a backend compiler object, so
    it remains available when a document contains only indexed families or
    effect interfaces.

    Parameters
    ----------
    module : Module
        The parsed module holding the binding.
    name : str
        The QIEC binding to describe.

    Returns
    -------
    str or None
        The compact signature, or ``None`` when ``name`` is not a QIEC
        binding of ``module``.
    """

    binding = qiec_binding_map(module).get(name)
    if binding is None:
        return None
    return _render_qiec_binding_signature(binding, name)

render_signature

render_signature(compiler: Compiler | None, name: str) -> str | None

Return the GHCi-style name :: type (or object NAME : ... for type-level bindings) for a top-level name, or None when the compiler is absent or the name is unknown.

This is the shared entry point used by both the REPL (:type / :kind / bare-expression fallback) and the LSP server's hover panel: by routing every surface that wants a one-line signature through the same function, a binding looks identical regardless of whether the user is in the TUI or hovering in an editor.

PARAMETER DESCRIPTION
compiler

The compiler holding the elaborated environment.

TYPE: Compiler or None

name

The top-level name to describe.

TYPE: str

RETURNS DESCRIPTION
str or None

The one-line signature, or None when there is no compiler or the name is unbound.

Source code in src/quivers/cli/repl_session.py
def render_signature(compiler: Compiler | None, name: str) -> str | None:
    """Return the GHCi-style ``name :: type`` (or ``object NAME : ...``
    for type-level bindings) for a top-level name, or ``None`` when
    the compiler is absent or the name is unknown.

    This is the shared entry point used by both the REPL (``:type``
    / ``:kind`` / bare-expression fallback) and the LSP server's
    hover panel: by routing every surface that wants a one-line
    signature through the same function, a binding looks identical
    regardless of whether the user is in the TUI or hovering in an
    editor.

    Parameters
    ----------
    compiler : Compiler or None
        The compiler holding the elaborated environment.
    name : str
        The top-level name to describe.

    Returns
    -------
    str or None
        The one-line signature, or ``None`` when there is no compiler
        or the name is unbound.
    """
    if compiler is None:
        return None
    s = ReplSession()
    s._compiler = compiler
    s._module = getattr(compiler, "_module", Module(statements=()))
    line = s._value_line_for_name(name)
    if line is not None:
        return line
    return s._type_line_for_name(name)

run_tui

run_tui(session: ReplSession) -> int

Run the Textual REPL front end on session.

PARAMETER DESCRIPTION
session

The session that evaluates each input.

TYPE: ReplSession

RETURNS DESCRIPTION
int

The process exit status, 0 once the app exits.

Source code in src/quivers/cli/repl_tui.py
def run_tui(session: ReplSession) -> int:
    """Run the Textual REPL front end on ``session``.

    Parameters
    ----------
    session : ReplSession
        The session that evaluates each input.

    Returns
    -------
    int
        The process exit status, ``0`` once the app exits.
    """
    app = _build_tui_app(session)
    app.run()  # type: ignore[attr-defined]
    return 0

__getattr__

__getattr__(name: str) -> Callable[[ReplSession], int]

Bind the re-exports whose modules need optional dependencies.

Importing run_tui loads Textual, which only the repl extra installs, so the package binds it on first access rather than at import time.

PARAMETER DESCRIPTION
name

The attribute being looked up.

TYPE: str

RETURNS DESCRIPTION
Callable[[ReplSession], int]

The lazily bound front end.

RAISES DESCRIPTION
AttributeError

When name is not a lazily bound re-export.

Source code in src/quivers/cli/__init__.py
def __getattr__(name: str) -> Callable[[ReplSession], int]:
    """Bind the re-exports whose modules need optional dependencies.

    Importing `run_tui` loads Textual, which only the ``repl`` extra
    installs, so the package binds it on first access rather than at
    import time.

    Parameters
    ----------
    name : str
        The attribute being looked up.

    Returns
    -------
    Callable[[ReplSession], int]
        The lazily bound front end.

    Raises
    ------
    AttributeError
        When ``name`` is not a lazily bound re-export.
    """
    if name == "run_tui":
        repl_tui = importlib.import_module("quivers.cli.repl_tui")
        return repl_tui.run_tui
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

build_parser

build_parser() -> ArgumentParser

The qvr command line's parser, every subcommand included.

RETURNS DESCRIPTION
ArgumentParser

The parser; its subcommand is cmd.

Source code in src/quivers/cli/__init__.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
def build_parser() -> argparse.ArgumentParser:
    """The ``qvr`` command line's parser, every subcommand included.

    Returns
    -------
    argparse.ArgumentParser
        The parser; its subcommand is ``cmd``.
    """
    parser = argparse.ArgumentParser(prog="qvr", description=__doc__)
    parser.add_argument(
        "--version", action="version", version=f"%(prog)s {__version__}"
    )
    sub = parser.add_subparsers(dest="cmd", required=True)

    check = sub.add_parser(
        "check",
        help="Parse + compile .qvr files and report diagnostics.",
    )
    check.add_argument(
        "files",
        nargs="+",
        help=".qvr files or dotted module paths (resolved below --root).",
    )
    check.add_argument(
        "--root",
        action="append",
        default=None,
        metavar="DIR",
        help=(
            "A directory module paths are relative to; repeatable. A file's "
            "own directory, or the working directory for a module path, by "
            "default."
        ),
    )
    check.add_argument(
        "--json",
        action="store_true",
        help="Emit structured JSON diagnostics on stdout.",
    )
    check.add_argument(
        "--target",
        default=None,
        help="Also diagnose the features this transpile target lacks.",
    )

    repl = sub.add_parser(
        "repl",
        help="Start an interactive type-exploration REPL.",
    )
    repl.add_argument(
        "file",
        nargs="?",
        default=None,
        help="Optional .qvr file to :load on startup.",
    )
    repl.add_argument(
        "--plain",
        action="store_true",
        help="Use the prompt_toolkit single-line front end instead of the TUI.",
    )
    repl.add_argument(
        "--target",
        default=None,
        metavar="TARGET",
        help=(
            "Report this transpile target's capability diagnostics on :load "
            "and :reload, as `qvr check --target` does."
        ),
    )

    run = sub.add_parser(
        "run",
        help="Execute one entry point: a `define` computation or a `program`.",
    )
    run.add_argument(
        "file",
        help=(
            "The .qvr file or dotted module path, optionally followed by "
            ":ENTRY (pkg.experiments.boolean:fit)."
        ),
    )
    run.add_argument(
        "--root",
        action="append",
        default=None,
        metavar="DIR",
        help="A directory module paths are relative to; repeatable.",
    )
    run.add_argument(
        "computation",
        nargs="?",
        default=None,
        help=(
            "Entry point to execute: a `define` computation or a `program`. "
            "Omit it, or pass --list, to list the file's entry points."
        ),
    )
    run.add_argument(
        "arguments",
        nargs="*",
        help="Value arguments as JSON literals, in declaration order.",
    )
    run.add_argument(
        "--list",
        action="store_true",
        help="List the file's entry points with their signatures and exit.",
    )
    run.add_argument(
        "--static",
        action="append",
        default=[],
        metavar="NAME=TERM",
        help="Closed static specialization; repeat once per telescope binder.",
    )
    run.add_argument(
        "--data",
        action="append",
        default=[],
        metavar="NAME=JSON",
        help=(
            "A program parameter by name (its data, an observation, an "
            "index map, or a scalar); repeatable."
        ),
    )
    run.add_argument(
        "--site",
        action="append",
        default=[],
        metavar="NAME=JSON",
        help=(
            "Condition a program's sample site on a value; every other site "
            "is drawn. NAME is a site of the program or a path pattern over "
            "site addresses, such as 'Discourse(*).fit.prior'. Repeatable."
        ),
    )
    run.add_argument(
        "--replay",
        default=None,
        metavar="RECORD",
        help=(
            "Condition a program on the site values of a run record written "
            "by `qvr run --json`, matched to the program's sites by identity, "
            "so a record survives renamed modules, declarations, and sites."
        ),
    )
    run.add_argument(
        "--seed",
        type=int,
        default=None,
        metavar="N",
        help="Seed the reference generator a program run draws with.",
    )
    run.add_argument(
        "--cache",
        action="store_true",
        help=(
            "Reuse a stored run with the same entry hash, arguments, data, "
            "sites, options, seed, and engine from the project cache, or "
            "store this one; requires --seed."
        ),
    )
    run.add_argument(
        "--runtime",
        default=None,
        metavar="FILE.json",
        help="Explicit JSON runtime-provider configuration.",
    )
    run.add_argument(
        "--fuel",
        type=int,
        default=None,
        metavar="STEPS",
        help=(
            "Stop after this many evaluation steps with a qiec-run-fuel "
            "diagnostic; recursion may otherwise run forever."
        ),
    )
    run.add_argument(
        "--exact",
        action="store_true",
        help=(
            "Compute a computation's reals exactly, as rationals; an operation "
            "the rationals are not closed under (exp, log, sqrt, ...) is refused."
        ),
    )
    run.add_argument(
        "--holes",
        action="store_true",
        help=(
            "Run a computation of a module with typed holes on the reference "
            "machine: a result that needs a hole's value is reported as "
            "indeterminate. Without it, a module with holes is refused."
        ),
    )
    run.add_argument(
        "--trace",
        action="store_true",
        help="Write stable execution trace events to stderr.",
    )
    run.add_argument(
        "--json",
        action="store_true",
        help="Emit the result, diagnostics, and trace as JSON.",
    )

    lsp = sub.add_parser(
        "lsp",
        help="Run the QVR Language Server (LSP 3.17 over stdio).",
    )
    lsp.add_argument(
        "--tcp",
        type=int,
        default=None,
        metavar="PORT",
        help="Bind to TCP port instead of stdio.",
    )
    lsp.add_argument(
        "--target",
        default=None,
        help="Diagnose the features this transpile target lacks.",
    )

    migrate = sub.add_parser(
        "migrate",
        help="Migrate .qvr files and the QVR blocks of Markdown files between "
        "grammar revisions.",
    )
    migrate.add_argument(
        "--from",
        dest="from_ref",
        default=None,
        help="Source grammar revision (git tag or commit id). Required when "
        "migrating because QVR source does not yet carry a version marker.",
    )
    migrate.add_argument(
        "--to",
        dest="to_ref",
        default=None,
        help="Target grammar revision. Defaults to the upcoming "
        "release (last entry on the chain).",
    )
    migrate.add_argument(
        "--dry-run",
        action="store_true",
        help="Report what would change without writing output.",
    )
    migrate.add_argument(
        "--output",
        default=None,
        help="Write migrated files under this directory rather than "
        "overwriting in place.",
    )
    migrate.add_argument(
        "--check",
        action="store_true",
        help="Validate the migration chain against the panproto VCS schema "
        "diff, converter coverage, and asserted identity hops. Non-zero "
        "exit on uncovered or unexpected drift. Does not migrate files and "
        "does not require --from.",
    )
    migrate.add_argument(
        "--dependency",
        default=None,
        metavar="PKG@OLD..NEW",
        help="Migrate the package's modules, and the run records given as paths, "
        "from one version of a dependency to another along its interface lens.",
    )
    migrate.add_argument(
        "--package",
        default=None,
        metavar="DIR",
        help="With --dependency: the package directory (default: the one "
        "containing the working directory).",
    )
    migrate.add_argument(
        "paths",
        nargs="*",
        help=".qvr files, Markdown or .qvr.md files, or directories to migrate; "
        "with --dependency, run records.",
    )

    kernel = sub.add_parser(
        "kernel",
        help="Jupyter kernel: install kernelspec or run a kernel.",
    )
    kernel_sub = kernel.add_subparsers(dest="kernel_cmd", required=True)
    kernel_install = kernel_sub.add_parser(
        "install", help="Register the `quivers` Jupyter kernelspec."
    )
    kernel_install.add_argument(
        "--user",
        action="store_true",
        help="Install to the user kernel directory instead of system.",
    )
    kernel_install.add_argument(
        "--prefix",
        default=None,
        help="Install kernelspec under PREFIX/share/jupyter/kernels.",
    )
    kernel_sub.add_parser(
        "run", help="Run as a Jupyter kernel (invoked by Jupyter itself)."
    )
    kernel_run_f = kernel_sub.add_parser(
        "_run_f",
        help=argparse.SUPPRESS,
    )
    kernel_run_f.add_argument("connection_file")

    transpile_sub = sub.add_parser(
        "transpile",
        help="Transpile a .qvr file to other probabilistic-programming "
        "languages (Stan, NumPyro, Pyro, PyMC, ...).",
    )
    transpile_sub.add_argument(
        "file",
        nargs="?",
        default=None,
        help="The .qvr file or dotted module path.",
    )
    transpile_sub.add_argument(
        "--root",
        action="append",
        default=None,
        metavar="DIR",
        help="A directory module paths are relative to; repeatable.",
    )

    doc = sub.add_parser(
        "doc",
        help="Render the public interface of each module.",
    )
    doc.add_argument(
        "modules",
        nargs="+",
        help=".qvr files or dotted module paths (resolved below --root).",
    )
    doc.add_argument(
        "--root",
        action="append",
        default=None,
        metavar="DIR",
        help="A directory module paths are relative to; repeatable.",
    )
    doc.add_argument(
        "--format",
        choices=("markdown", "json"),
        default="markdown",
        help="Markdown pages (default) or the interface artifacts as JSON.",
    )
    doc.add_argument(
        "--imports",
        action="store_true",
        help="Also render every module the named modules import.",
    )
    transpile_sub.add_argument(
        "--to",
        default=None,
        help="Target backend name (e.g. 'stan', 'numpyro').",
    )
    transpile_sub.add_argument(
        "--to-all",
        action="store_true",
        help="Transpile to every registered backend.",
    )
    transpile_sub.add_argument(
        "--list-targets",
        action="store_true",
        help="List every registered backend and exit.",
    )
    transpile_sub.add_argument(
        "-o",
        "--output",
        default=None,
        help="Write the single-target output to this path instead of stdout.",
    )
    transpile_sub.add_argument(
        "--index-map",
        default=None,
        metavar="FILE",
        help="Also write the layout of every tensor-typed parameter (each "
        "axis's name, extent, and coordinates in position order) as JSON.",
    )
    transpile_sub.add_argument(
        "-d",
        "--out-dir",
        default=None,
        help="With --to-all, write one file per backend under this "
        "directory (named <stem>.<extension>).",
    )

    test = sub.add_parser(
        "test",
        help="Run the tests, properties, and examples of .qvr modules.",
    )
    test.add_argument(
        "paths",
        nargs="+",
        help="Module files and package directories to test.",
    )
    test.add_argument(
        "--json",
        action="store_true",
        help="Print the machine-readable report on stdout.",
    )
    test.add_argument(
        "--no-cache",
        action="store_true",
        help="Run every test, even one whose pass is cached for its content.",
    )
    test.add_argument(
        "--match",
        default=None,
        metavar="TEXT",
        help="Run only the tests whose title contains TEXT.",
    )
    test.add_argument(
        "--mutate",
        action="store_true",
        help=(
            "Run each module's tests against every mutant of its rules, "
            "lexical entries, and constants, and report the survivors."
        ),
    )
    test.add_argument(
        "--operators",
        default=None,
        metavar="NAMES",
        help=(
            "With --mutate, the comma-separated mutation operators to run: "
            "drop-rule, drop-entry, swap-category, constant (all by default)."
        ),
    )
    test.add_argument(
        "--mutate-module",
        action="append",
        default=None,
        metavar="MODULE",
        help=(
            "With --mutate, mutate the code of this imported module (repeatable) "
            "instead of the tested module's own, under the tested module's tests."
        ),
    )

    hash_sub = sub.add_parser(
        "hash",
        help="Print the content hashes of checked .qvr files.",
    )
    hash_sub.add_argument(
        "files",
        nargs="*",
        help=".qvr files; with --check-migrations, files or directories "
        "(the corpus when omitted).",
    )
    hash_sub.add_argument("--json", action="store_true", help="Print JSON.")
    hash_sub.add_argument(
        "--normal-form",
        default=None,
        metavar="KIND:NAME",
        help="Print the canonical core form one declaration's hash digests.",
    )
    hash_sub.add_argument(
        "--check-migrations",
        action="store_true",
        help="Check that every syntactic migration hop preserves every core hash.",
    )

    cache_sub = sub.add_parser(
        "cache",
        help="Inspect and manage the project's persistent cache.",
    )
    cache_sub.add_argument(
        "--dir",
        default=None,
        metavar="PATH",
        help="The cache directory; default $QVR_CACHE_DIR, else .qvr/cache "
        "at the project root.",
    )
    cache_sub.add_argument("--json", action="store_true", help="Print JSON.")
    cache_actions = cache_sub.add_subparsers(dest="cache_cmd")
    cache_actions.add_parser("info", help="Show the directory, limit, and usage.")
    cache_list = cache_actions.add_parser(
        "list", help="List entries, most recently used first."
    )
    cache_list.add_argument("--namespace", default=None, help="Only this namespace.")
    cache_clear = cache_actions.add_parser("clear", help="Delete entries.")
    cache_clear.add_argument("--namespace", default=None, help="Only this namespace.")
    cache_prune = cache_actions.add_parser(
        "prune", help="Evict unused entries, then the least recently used."
    )
    cache_prune.add_argument(
        "--max-size",
        default=None,
        metavar="SIZE",
        help="Evict down to this size (default: the limit).",
    )
    cache_prune.add_argument(
        "--older-than",
        default=None,
        metavar="AGE",
        help="First evict entries unused for this long (e.g. 7d).",
    )
    cache_limit = cache_actions.add_parser("limit", help="Show or set the size limit.")
    cache_limit.add_argument(
        "size", nargs="?", default=None, metavar="SIZE", help="The new limit (e.g. 2G)."
    )

    add_package_parsers(sub)
    add_experiment_parser(sub)
    add_weave_parser(sub)
    return parser

main

main(argv: Sequence[str] | None = None) -> int

Run the qvr command line.

PARAMETER DESCRIPTION
argv

The arguments after the program name; sys.argv's when None.

TYPE: Sequence[str] | None DEFAULT: None

RETURNS DESCRIPTION
int

The process exit status of the selected subcommand.

Source code in src/quivers/cli/__init__.py
def main(argv: Sequence[str] | None = None) -> int:
    """Run the ``qvr`` command line.

    Parameters
    ----------
    argv : Sequence[str] | None
        The arguments after the program name; ``sys.argv``'s when ``None``.

    Returns
    -------
    int
        The process exit status of the selected subcommand.
    """
    parser = build_parser()
    args = parser.parse_args(argv)
    if args.cmd == "check":
        return check_main(
            args.files,
            json_output=args.json,
            target=args.target,
            roots=search_roots(args.root),
        )
    module_name = _COMMAND_MODULES.get(args.cmd)
    if module_name is not None:
        command: Callable[[argparse.Namespace], int] = importlib.import_module(
            module_name
        ).main
        return command(args)
    parser.print_help(sys.stderr)
    return 2

migrations

Registry of structural one-hop .qvr source migrations.

Each adjacent-pair migrator is a callable bytes -> bytes built on the panproto pipeline in quivers.cli.migrations._common: parse with the source revision's tree-sitter parser, build the target schema by walking the source parse tree and emitting target vertices/edges/constraints, then emit canonical target bytes via the target revision's emit_pretty. The third stage is grammar- bound by panproto: a target schema that does not satisfy the target grammar's rules cannot emit.

The CHAIN tuple lists releases in chronological order with "HEAD" always last. Each adjacent pair (CHAIN[i], CHAIN[i+1]) must have a registered migrator in MIGRATORS. compose_migration walks CHAIN between any two listed releases and composes the intermediate hops into a single bytes -> bytes callable.

During development the newest released revision migrates to "HEAD" through one release hop package (v<released>_to_v<next>), whose feature modules each contribute span-edit collectors; see quivers.cli.migrations._features. That edge is open: the working grammar may or may not differ from the released one yet.

To prepare a release:

  1. Freeze the working grammar as an immutable parser snapshot under grammars/qvr/vcs/parsers/v<next> and pin its asset hashes and panproto schema commit in quivers._grammar_manifest.
  2. Set the release hop's TARGET_REVISION to "v<next>".
  3. Insert "v<next>" immediately before "HEAD" in CHAIN and register the explicit identity migrator for ("v<next>", "HEAD").

The qvr migrate CLI consumes compose_migration and is agnostic to which pairs are registered.

CHAIN module-attribute

CHAIN: tuple[str, ...] = ('v0.2.0', 'v0.3.0', 'v0.4.0', 'v0.5.0', 'v0.6.0', 'v0.7.0', 'v0.9.0', 'v0.10.0', 'v0.11.0', 'v0.14.0', 'v0.15.0', 'v0.16.0', 'v0.17.0', 'v0.18.0', 'v0.19.0', 'v0.62.0', 'v0.64.2', 'v0.65.0', 'v0.66.0', 'v0.67.0', 'v0.68.0', 'v0.69.0', 'v0.70.0', _hop_weighted_total.SOURCE_REVISION, _hop_score_heads.SOURCE_REVISION, _hop_law_values.SOURCE_REVISION, _hop_model_binds.SOURCE_REVISION, _hop_site_groups.SOURCE_REVISION, _hop_site_groups.TARGET_REVISION, _hop_release.TARGET_REVISION, 'HEAD')

The QVR grammar releases a migration can start or end at, oldest first, with "HEAD" (the current grammar) always last.

MIGRATORS module-attribute

MIGRATORS: dict[tuple[str, str], _Migrator] = {('v0.2.0', 'v0.3.0'): _hop_2_3.migrate, ('v0.3.0', 'v0.4.0'): _hop_3_4.migrate, ('v0.4.0', 'v0.5.0'): _hop_4_5.migrate, ('v0.5.0', 'v0.6.0'): _hop_5_6.migrate, ('v0.6.0', 'v0.7.0'): _hop_6_7.migrate, ('v0.7.0', 'v0.9.0'): _hop_7_9.migrate, ('v0.9.0', 'v0.10.0'): _identity.migrator('v0.9.0', 'v0.10.0', resolve_commit=commit_id), ('v0.10.0', 'v0.11.0'): _hop_10_11.migrate, ('v0.11.0', 'v0.14.0'): _hop_11_14.migrate, ('v0.14.0', 'v0.15.0'): _hop_14_15.migrate, ('v0.15.0', 'v0.16.0'): _identity.migrator('v0.15.0', 'v0.16.0', resolve_commit=commit_id), ('v0.16.0', 'v0.17.0'): _identity.migrator('v0.16.0', 'v0.17.0', resolve_commit=commit_id), ('v0.17.0', 'v0.18.0'): _identity.migrator('v0.17.0', 'v0.18.0', resolve_commit=commit_id), ('v0.18.0', 'v0.19.0'): _hop_18_19.migrate, ('v0.19.0', 'v0.62.0'): _hop_19_62.migrate, ('v0.62.0', 'v0.64.2'): _hop_62_64.migrate, ('v0.64.2', 'v0.65.0'): _hop_64_65.migrate, ('v0.65.0', 'v0.66.0'): _identity.migrator('v0.65.0', 'v0.66.0', resolve_commit=commit_id), ('v0.66.0', 'v0.67.0'): _identity.migrator('v0.66.0', 'v0.67.0', resolve_commit=commit_id), ('v0.67.0', 'v0.68.0'): _hop_67_68.migrate, ('v0.68.0', 'v0.69.0'): _identity.migrator('v0.68.0', 'v0.69.0', resolve_commit=commit_id), ('v0.69.0', 'v0.70.0'): _identity.migrator('v0.69.0', 'v0.70.0', resolve_commit=commit_id), ('v0.70.0', _hop_weighted_total.SOURCE_REVISION): _hop_weighted_total.from_release, (_hop_weighted_total.SOURCE_REVISION, _hop_score_heads.SOURCE_REVISION): _hop_weighted_total.migrate, (_hop_score_heads.SOURCE_REVISION, _hop_law_values.SOURCE_REVISION): _hop_score_heads.migrate, (_hop_law_values.SOURCE_REVISION, _hop_law_values.TARGET_REVISION): _hop_law_values.migrate, (_hop_model_binds.SOURCE_REVISION, _hop_site_groups.SOURCE_REVISION): _hop_model_binds.migrate, (_hop_site_groups.SOURCE_REVISION, _hop_site_groups.TARGET_REVISION): _hop_site_groups.migrate, (_hop_release.SOURCE_REVISION, _hop_release.TARGET_REVISION): _hop_release.migrate, (_hop_release.TARGET_REVISION, 'HEAD'): _identity.migrator(_hop_release.TARGET_REVISION, 'HEAD', resolve_commit=commit_id)}

The one-hop migrator registered for each adjacent pair of CHAIN, a bytes -> bytes rewrite of .qvr source.

COVERAGE module-attribute

COVERAGE: dict[tuple[str, str], frozenset[str]] = {('v0.2.0', 'v0.3.0'): _hop_2_3.SOURCE_RULE_COVERAGE, ('v0.3.0', 'v0.4.0'): _hop_3_4.SOURCE_RULE_COVERAGE, ('v0.4.0', 'v0.5.0'): _hop_4_5.SOURCE_RULE_COVERAGE, ('v0.5.0', 'v0.6.0'): _hop_5_6.SOURCE_RULE_COVERAGE, ('v0.6.0', 'v0.7.0'): _hop_6_7.SOURCE_RULE_COVERAGE, ('v0.7.0', 'v0.9.0'): _hop_7_9.SOURCE_RULE_COVERAGE, ('v0.9.0', 'v0.10.0'): _identity.SOURCE_RULE_COVERAGE, ('v0.10.0', 'v0.11.0'): _hop_10_11.SOURCE_RULE_COVERAGE, ('v0.11.0', 'v0.14.0'): _hop_11_14.SOURCE_RULE_COVERAGE, ('v0.14.0', 'v0.15.0'): _hop_14_15.SOURCE_RULE_COVERAGE, ('v0.15.0', 'v0.16.0'): _identity.SOURCE_RULE_COVERAGE, ('v0.16.0', 'v0.17.0'): _identity.SOURCE_RULE_COVERAGE, ('v0.17.0', 'v0.18.0'): _identity.SOURCE_RULE_COVERAGE, ('v0.18.0', 'v0.19.0'): _hop_18_19.SOURCE_RULE_COVERAGE, ('v0.19.0', 'v0.62.0'): _hop_19_62.SOURCE_RULE_COVERAGE, ('v0.62.0', 'v0.64.2'): _hop_62_64.SOURCE_RULE_COVERAGE, ('v0.64.2', 'v0.65.0'): _hop_64_65.SOURCE_RULE_COVERAGE, ('v0.65.0', 'v0.66.0'): _identity.SOURCE_RULE_COVERAGE, ('v0.66.0', 'v0.67.0'): _identity.SOURCE_RULE_COVERAGE, ('v0.67.0', 'v0.68.0'): _hop_67_68.SOURCE_RULE_COVERAGE, ('v0.68.0', 'v0.69.0'): _identity.SOURCE_RULE_COVERAGE, ('v0.69.0', 'v0.70.0'): _identity.SOURCE_RULE_COVERAGE, ('v0.70.0', _hop_weighted_total.SOURCE_REVISION): frozenset(), (_hop_weighted_total.SOURCE_REVISION, _hop_score_heads.SOURCE_REVISION): _hop_weighted_total.SOURCE_RULE_COVERAGE, (_hop_score_heads.SOURCE_REVISION, _hop_law_values.SOURCE_REVISION): _hop_score_heads.SOURCE_RULE_COVERAGE, (_hop_law_values.SOURCE_REVISION, _hop_law_values.TARGET_REVISION): _hop_law_values.SOURCE_RULE_COVERAGE, (_hop_model_binds.SOURCE_REVISION, _hop_site_groups.SOURCE_REVISION): _hop_model_binds.SOURCE_RULE_COVERAGE, (_hop_site_groups.SOURCE_REVISION, _hop_site_groups.TARGET_REVISION): _hop_site_groups.SOURCE_RULE_COVERAGE, (_hop_release.SOURCE_REVISION, _hop_release.TARGET_REVISION): _hop_release.SOURCE_RULE_COVERAGE, (_hop_release.TARGET_REVISION, 'HEAD'): _identity.SOURCE_RULE_COVERAGE}

The source-side grammar rules each hop's converters cover, keyed by adjacent pair of CHAIN. vcs_coverage_report checks these against the schema diff between the two revisions.

SEMANTIC_HOPS module-attribute

SEMANTIC_HOPS: dict[tuple[str, str], str] = {(_hop_release.SOURCE_REVISION, _hop_release.TARGET_REVISION): _RELEASE_SEMANTICS} if _RELEASE_SEMANTICS else {}

The adjacent pairs of CHAIN whose hop may change the checked meaning of the source, with the reason. A hop absent from this table must preserve the content hash of every declaration it rewrites.

IDENTITY_PAIRS module-attribute

IDENTITY_PAIRS: frozenset[tuple[str, str]] = _declared_identity_pairs()

The adjacent pairs of CHAIN whose grammars are identical, so that their registered migrator returns its source unchanged.

MigrationError

Bases: Exception

Raised when a requested migration cannot be composed, or when a source construct admits no rewrite under the target grammar.

BlameReport didactic-model

BlameReport(*, rule: str, introduced_at_commit: str | None, introduced_at_tag: str | None, last_present_at_commit: str | None, last_present_at_tag: str | None)

Bases: Model

Where in the grammar's history a rule first appeared or was last seen.

PARAMETER DESCRIPTION
rule

The tree-sitter rule name.

TYPE: str

introduced_at_commit

The commit that introduced the rule, when the VCS records one.

TYPE: str or None

introduced_at_tag

The release tag of that commit, when it has one.

TYPE: str or None

last_present_at_commit

The newest commit whose schema contains the rule.

TYPE: str or None

last_present_at_tag

The release tag of that commit, when it has one.

TYPE: str or None

DiffCoverageReport didactic-model

DiffCoverageReport(*, from_ref: str, to_ref: str, added_rules: tuple[str, ...], removed_rules: tuple[str, ...], uncovered_removed: tuple[str, ...])

Bases: Model

The schema diff between two revisions, classified against a hop's declared converters.

PARAMETER DESCRIPTION
from_ref

The source release.

TYPE: str

to_ref

The target release.

TYPE: str

added_rules

Grammar rules present at to_ref but not at from_ref.

TYPE: tuple[str, ...]

removed_rules

Grammar rules present at from_ref but not at to_ref.

TYPE: tuple[str, ...]

uncovered_removed

The removed rules that the hop declares no converter for.

TYPE: tuple[str, ...]

uncovered_removed instance-attribute

uncovered_removed: tuple[str, ...]

Rules removed at the target revision that are also absent from declared_converters. Each one is a source-side vertex kind that the migrator's dispatch passes through as a structural clone, which emit_pretty then misrenders or drops. These are the actionable misses.

is_complete property

is_complete: bool

Whether every removed rule has a converter.

format

format() -> str

Render the report for CLI display.

RETURNS DESCRIPTION
str

A multi-line summary of the added, removed, and uncovered rules.

Source code in src/quivers/cli/migrations/_vcs.py
def format(self) -> str:
    """Render the report for CLI display.

    Returns
    -------
    str
        A multi-line summary of the added, removed, and uncovered
        rules.
    """
    lines = [f"{self.from_ref} -> {self.to_ref}:"]
    if not self.added_rules and not self.removed_rules:
        lines.append("    (grammar identical; no diff)")
        return "\n".join(lines)
    if self.removed_rules:
        lines.append(f"    removed: {', '.join(self.removed_rules)}")
    if self.added_rules:
        lines.append(f"    added:   {', '.join(self.added_rules)}")
    if self.uncovered_removed:
        lines.append(
            f"    UNCOVERED removed rules (no converter): "
            f"{', '.join(self.uncovered_removed)}",
        )
    elif self.removed_rules:
        lines.append("    all removed rules have converters [OK]")
    return "\n".join(lines)

blame_kind

blame_kind(rule: str) -> BlameReport

Report when a tree-sitter rule was introduced or removed.

The migrators' failure path uses this to point at the release that needs a new converter.

PARAMETER DESCRIPTION
rule

The tree-sitter rule name.

TYPE: str

RETURNS DESCRIPTION
BlameReport

The rule's introduction and last appearance in the grammar's VCS history.

Source code in src/quivers/cli/migrations/_vcs.py
def blame_kind(rule: str) -> BlameReport:
    """Report when a tree-sitter rule was introduced or removed.

    The migrators' failure path uses this to point at the release that
    needs a new converter.

    Parameters
    ----------
    rule : str
        The tree-sitter rule name.

    Returns
    -------
    BlameReport
        The rule's introduction and last appearance in the grammar's
        VCS history.
    """
    repo = _open_repo()
    head = repo.head() or ""

    introduced_commit: str | None = None
    try:
        info = repo.blame_vertex(head, rule)
        introduced_commit = str(info.get("commit"))  # type: ignore[union-attr]
    except Exception:
        introduced_commit = None

    introduced_tag = (
        _tag_for_commit(repo, introduced_commit) if introduced_commit else None
    )

    # Walk log oldest-first, find the last commit whose schema
    # contains the rule. If the current HEAD schema contains it,
    # introduced_commit is the answer to both "introduced" and
    # "last present." Otherwise scan history.
    last_commit: str | None = None
    for entry in repo.log():
        cid = str(entry["id"])
        try:
            schema = repo.schema_at(cid)
        except Exception:
            continue
        if schema.has_vertex(rule):
            last_commit = cid
            break  # log() is newest-first; the first hit is the last presence.
    last_tag = _tag_for_commit(repo, last_commit) if last_commit else None

    return BlameReport(
        rule=rule,
        introduced_at_commit=introduced_commit,
        introduced_at_tag=introduced_tag,
        last_present_at_commit=last_commit,
        last_present_at_tag=last_tag,
    )

check_chain_coverage

check_chain_coverage(chain: tuple[str, ...], converters_by_pair: dict[tuple[str, str], frozenset[str]]) -> list[DiffCoverageReport]

Run diff_coverage on every adjacent pair of a chain.

PARAMETER DESCRIPTION
chain

Releases in chronological order.

TYPE: tuple[str, ...]

converters_by_pair

The source-side rule names each (from, to) hop declares it converts. A pair absent from the map has no converters, so every rule it removes surfaces as uncovered.

TYPE: dict[tuple[str, str], frozenset[str]]

RETURNS DESCRIPTION
list[DiffCoverageReport]

One report per adjacent pair, in chain order.

Source code in src/quivers/cli/migrations/_vcs.py
def check_chain_coverage(
    chain: tuple[str, ...],
    converters_by_pair: dict[tuple[str, str], frozenset[str]],
) -> list[DiffCoverageReport]:
    """Run `diff_coverage` on every adjacent pair of a chain.

    Parameters
    ----------
    chain : tuple[str, ...]
        Releases in chronological order.
    converters_by_pair : dict[tuple[str, str], frozenset[str]]
        The source-side rule names each ``(from, to)`` hop declares it
        converts. A pair absent from the map has no converters, so
        every rule it removes surfaces as uncovered.

    Returns
    -------
    list[DiffCoverageReport]
        One report per adjacent pair, in chain order.
    """
    reports: list[DiffCoverageReport] = []
    for i in range(len(chain) - 1):
        from_ref = chain[i]
        to_ref = chain[i + 1]
        decl = converters_by_pair.get((from_ref, to_ref), frozenset())
        reports.append(diff_coverage(from_ref, to_ref, decl))
    return reports

diff_coverage

diff_coverage(from_ref: str, to_ref: str, declared_converters: frozenset[str]) -> DiffCoverageReport

Diff two revisions' grammar schemas against a hop's converters.

A rule appearing in from_ref's schema but not in to_ref's is a removed rule. A removed rule that declared_converters does not list would pass through the migrator unconverted, likely producing incorrect output; such rules surface in uncovered_removed. Identity hops, whose revisions share a commit, report no diff.

PARAMETER DESCRIPTION
from_ref

The source release.

TYPE: str

to_ref

The target release.

TYPE: str

declared_converters

The source-side rule names the hop declares it converts.

TYPE: frozenset[str]

RETURNS DESCRIPTION
DiffCoverageReport

The classified diff.

Source code in src/quivers/cli/migrations/_vcs.py
def diff_coverage(
    from_ref: str,
    to_ref: str,
    declared_converters: frozenset[str],
) -> DiffCoverageReport:
    """Diff two revisions' grammar schemas against a hop's converters.

    A rule appearing in ``from_ref``'s schema but not in ``to_ref``'s
    is a removed rule. A removed rule that ``declared_converters``
    does not list would pass through the migrator unconverted, likely
    producing incorrect output; such rules surface in
    ``uncovered_removed``. Identity hops, whose revisions share a
    commit, report no diff.

    Parameters
    ----------
    from_ref : str
        The source release.
    to_ref : str
        The target release.
    declared_converters : frozenset[str]
        The source-side rule names the hop declares it converts.

    Returns
    -------
    DiffCoverageReport
        The classified diff.
    """
    repo = _open_repo()
    from_id = commit_id_for(from_ref) or _resolve_via_chain(repo, from_ref)
    to_id = commit_id_for(to_ref) or _resolve_via_chain(repo, to_ref)
    if from_id == to_id:
        return DiffCoverageReport(
            from_ref=from_ref,
            to_ref=to_ref,
            added_rules=(),
            removed_rules=(),
            uncovered_removed=(),
        )
    src_schema = repo.schema_at(from_id)
    tgt_schema = repo.schema_at(to_id)
    diff = panproto.diff_schemas(src_schema, tgt_schema)
    diff_dict = diff.to_dict()
    added = tuple(sorted(diff_dict.get("added_vertices", [])))
    removed = tuple(sorted(diff_dict.get("removed_vertices", [])))
    uncovered = tuple(r for r in removed if r not in declared_converters)
    return DiffCoverageReport(
        from_ref=from_ref,
        to_ref=to_ref,
        added_rules=added,
        removed_rules=removed,
        uncovered_removed=uncovered,
    )

commit_id

commit_id(ref: str) -> str

Resolve a release name to its pinned panproto VCS commit id.

The commit ids come from the schema-commit manifest and are computed once, on first call.

PARAMETER DESCRIPTION
ref

A release name in CHAIN, such as "v0.19.0" or "HEAD".

TYPE: str

RETURNS DESCRIPTION
str

The commit id, or "" when ref is not in CHAIN.

RAISES DESCRIPTION
MigrationError

When the manifest disagrees with CHAIN or with the VCS tags.

Source code in src/quivers/cli/migrations/__init__.py
def commit_id(ref: str) -> str:
    """Resolve a release name to its pinned panproto VCS commit id.

    The commit ids come from the schema-commit manifest and are
    computed once, on first call.

    Parameters
    ----------
    ref : str
        A release name in `CHAIN`, such as ``"v0.19.0"`` or ``"HEAD"``.

    Returns
    -------
    str
        The commit id, or ``""`` when ``ref`` is not in `CHAIN`.

    Raises
    ------
    MigrationError
        When the manifest disagrees with `CHAIN` or with the VCS tags.
    """
    if not _COMMIT_IDS:
        _COMMIT_IDS.update(_build_commit_index())
    return _COMMIT_IDS.get(ref, "")

vcs_coverage_report

vcs_coverage_report() -> list[DiffCoverageReport]

Check every registered hop against the grammar's schema diff.

For each adjacent pair of CHAIN, the report carries the schema diff between the two revisions and the removed source rules that the hop's COVERAGE entry does not cover. qvr migrate --check runs this, and a CI test can run it to catch a migrator that has fallen behind a grammar change.

RETURNS DESCRIPTION
list[DiffCoverageReport]

One report per adjacent pair of CHAIN, in chain order.

RAISES DESCRIPTION
MigrationError

When MIGRATORS, COVERAGE, or IDENTITY_PAIRS disagree with CHAIN or with the grammar manifest.

Source code in src/quivers/cli/migrations/__init__.py
def vcs_coverage_report() -> list[DiffCoverageReport]:
    """Check every registered hop against the grammar's schema diff.

    For each adjacent pair of `CHAIN`, the report carries the schema
    diff between the two revisions and the removed source rules that
    the hop's `COVERAGE` entry does not cover. ``qvr migrate --check``
    runs this, and a CI test can run it to catch a migrator that has
    fallen behind a grammar change.

    Returns
    -------
    list[DiffCoverageReport]
        One report per adjacent pair of `CHAIN`, in chain order.

    Raises
    ------
    MigrationError
        When `MIGRATORS`, `COVERAGE`, or `IDENTITY_PAIRS` disagree with
        `CHAIN` or with the grammar manifest.
    """
    identity_pairs = _validate_registry()
    reports: list[DiffCoverageReport] = []
    for i in range(len(CHAIN) - 1):
        from_ref = CHAIN[i]
        to_ref = CHAIN[i + 1]
        if (from_ref, to_ref) in identity_pairs:
            _identity.validate_identity_pair(from_ref, to_ref, resolve_commit=commit_id)
        decl = COVERAGE.get((from_ref, to_ref), frozenset())
        from_id = commit_id(from_ref)
        to_id = commit_id(to_ref)
        if from_id == to_id:
            reports.append(
                DiffCoverageReport(
                    from_ref=from_ref,
                    to_ref=to_ref,
                    added_rules=(),
                    removed_rules=(),
                    uncovered_removed=(),
                )
            )
            continue
        # Re-implement diff_coverage's body using the resolved
        # commit ids directly to avoid double-resolution.

        repo = _open_repo()
        src_schema = repo.schema_at(from_id)
        tgt_schema = repo.schema_at(to_id)
        diff_dict = panproto.diff_schemas(src_schema, tgt_schema).to_dict()
        added = _rule_names(diff_dict.get("added_vertices", []))
        removed = _rule_names(diff_dict.get("removed_vertices", []))
        uncovered = tuple(r for r in removed if r not in decl)
        reports.append(
            DiffCoverageReport(
                from_ref=from_ref,
                to_ref=to_ref,
                added_rules=added,
                removed_rules=removed,
                uncovered_removed=uncovered,
            )
        )
    return reports

compose_migration

compose_migration(from_ref: str, to_ref: str) -> _Migrator

Compose the hops between two releases into one migrator.

PARAMETER DESCRIPTION
from_ref

The source release, a member of CHAIN.

TYPE: str

to_ref

The target release, a member of CHAIN no earlier than from_ref.

TYPE: str

RETURNS DESCRIPTION
Callable[[bytes], bytes]

A rewrite of .qvr source from from_ref's grammar to to_ref's, applying every registered hop in between.

RAISES DESCRIPTION
MigrationError

When either release is not in CHAIN, when to_ref precedes from_ref, or when a hop between them has no migrator.

Source code in src/quivers/cli/migrations/__init__.py
def compose_migration(from_ref: str, to_ref: str) -> _Migrator:
    """Compose the hops between two releases into one migrator.

    Parameters
    ----------
    from_ref : str
        The source release, a member of `CHAIN`.
    to_ref : str
        The target release, a member of `CHAIN` no earlier than
        ``from_ref``.

    Returns
    -------
    Callable[[bytes], bytes]
        A rewrite of ``.qvr`` source from ``from_ref``'s grammar to
        ``to_ref``'s, applying every registered hop in between.

    Raises
    ------
    MigrationError
        When either release is not in `CHAIN`, when ``to_ref`` precedes
        ``from_ref``, or when a hop between them has no migrator.
    """
    pairs = _chain_slice(from_ref, to_ref)
    if not pairs:
        return _identity.migrator(from_ref, to_ref, resolve_commit=commit_id)
    missing = [pair for pair in pairs if pair not in MIGRATORS]
    if missing:
        raise MigrationError(
            "missing migrator(s) for pair(s): "
            + ", ".join(f"{a} -> {b}" for a, b in missing),
        )
    migrators = [MIGRATORS[pair] for pair in pairs]

    def _composite(source: bytes) -> bytes:
        for step in migrators:
            source = step(source)
        return source

    return _composite

available_targets

available_targets(from_ref: str) -> tuple[str, ...]

List the releases a migration from from_ref can target.

PARAMETER DESCRIPTION
from_ref

The source release.

TYPE: str

RETURNS DESCRIPTION
tuple[str, ...]

from_ref and every later release of CHAIN, or the empty tuple when from_ref is not in CHAIN.

Source code in src/quivers/cli/migrations/__init__.py
def available_targets(from_ref: str) -> tuple[str, ...]:
    """List the releases a migration from ``from_ref`` can target.

    Parameters
    ----------
    from_ref : str
        The source release.

    Returns
    -------
    tuple[str, ...]
        ``from_ref`` and every later release of `CHAIN`, or the empty
        tuple when ``from_ref`` is not in `CHAIN`.
    """
    if from_ref not in CHAIN:
        return ()
    i = CHAIN.index(from_ref)
    return CHAIN[i:]

The frozen 0.72.0 to 0.73.0 release hop is a package of feature modules. It loads them in name order into FEATURES and applies them over one parse of each file. The following hop from v0.73.0 to HEAD is an identity until development opens a new release hop (changing the QVR language).

v0_72_0_to_v0_73_0

Migrate v0.72.0 source to the v0.73.0 grammar through every feature's rewrites.

The modules of this package each describe one language feature as a quivers.cli.migrations._features.Feature: the span-edit collectors that rewrite the feature's v0.72.0 surface, the v0.72.0 rules they translate, the released forms that keep their spelling and meaning, the exact rewrites and refusals the feature promises, and the keywords it adds. The hop loads every module that defines FEATURE, in module-name order, and runs all of their collectors over one v0.72.0 parse of each file. Edits from different features never overlap; an overlap is refused rather than ordered.

A file is migrated in four steps. It must parse at v0.72.0 without recovery vertices. Every feature's collectors then return byte span edits, or refuse a construct with its line, column, and replacement. The edits are checked pairwise and applied. The result must parse at the target revision without recovery vertices and must not end a line in whitespace that the source did not. Source that uses none of the rewritten constructs is returned byte for byte.

SOURCE_REVISION module-attribute

SOURCE_REVISION = 'v0.72.0'

The released grammar revision the hop migrates from.

TARGET_REVISION module-attribute

TARGET_REVISION = 'v0.73.0'

The released grammar revision the hop migrates to.

FEATURES module-attribute

FEATURES: tuple[Feature, ...] = discover_features(__name__, __path__)

Every feature of the hop, in composition order.

SOURCE_RULE_COVERAGE module-attribute

SOURCE_RULE_COVERAGE: frozenset[str] = frozenset().union(*(feature.source_rule_coverage for feature in FEATURES))

The v0.72.0 rules translated by some feature's collectors.

SEMANTIC_REASONS module-attribute

SEMANTIC_REASONS: dict[str, str] = {feature.name: feature.semantic for feature in FEATURES if feature.semantic}

Each feature whose rewrites change checked meaning, with the reason.

migrate

migrate(source: bytes) -> bytes

Migrate one v0.72.0 file through every feature's rewrites.

PARAMETER DESCRIPTION
source

A complete file in the v0.72.0 surface.

TYPE: bytes

RETURNS DESCRIPTION
bytes

The complete file in the target surface.

RAISES DESCRIPTION
MigrationError

If the source is not v0.72.0 surface, a feature refuses one of its constructs, two features' edits overlap, or the output does not parse at the target revision.

Source code in src/quivers/cli/migrations/v0_72_0_to_v0_73_0/__init__.py
def migrate(source: bytes) -> bytes:
    """Migrate one v0.72.0 file through every feature's rewrites.

    Parameters
    ----------
    source : bytes
        A complete file in the v0.72.0 surface.

    Returns
    -------
    bytes
        The complete file in the target surface.

    Raises
    ------
    quivers.cli.migrations._common.MigrationError
        If the source is not v0.72.0 surface, a feature refuses one of its
        constructs, two features' edits overlap, or the output does not
        parse at the target revision.
    """
    return migrate_with(
        FEATURES,
        source,
        source_revision=SOURCE_REVISION,
        target_revision=TARGET_REVISION,
    )

lsp

QVR Language Server.

Public entry: build_server returns a configured pygls LanguageServer that speaks LSP 3.17 over stdio. The qvr lsp subcommand wraps it with stdio and TCP plumbing.

The server reuses every analytic component the REPL uses: per-document state in the style of ReplSession, tokenize for semantic tokens, and all_completions for completion. There is no duplicate parser, type-checker, or token vocabulary.

SERVER_NAME module-attribute

SERVER_NAME = 'qvr-lsp'

The server name reported to clients and attached to diagnostics.

SERVER_VERSION module-attribute

SERVER_VERSION = __version__

The server version reported to clients in the initialize response.

HoleFill didactic-model

HoleFill(*, title: str, text: str)

Bases: Model

One way to fill a hole.

PARAMETER DESCRIPTION
title

What the editor shows, Fill ?x with y.

TYPE: str

text

The text that replaces the hole's span.

TYPE: str

HoleSpan didactic-model

HoleSpan(*, line: int, start: int, end: int, declaration: bool = False)

Bases: Model

Where a hole is written, in 0-based lines and character columns.

PARAMETER DESCRIPTION
line

The line of its first character.

TYPE: int

start

The column of its first character.

TYPE: int

end

The column just past its last character, on the same line.

TYPE: int

declaration

Whether the hole is a declaration hole ?f(..) : T, whose span is the declaration's header.

TYPE: bool DEFAULT: False

NotationTarget didactic-model

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

Bases: Model

Where a production is declared.

PARAMETER DESCRIPTION
file

Its file, or empty for the document itself.

TYPE: str DEFAULT: ''

line

Its 0-based line in that file.

TYPE: int

col

Its 0-based column.

TYPE: int

length

The length of the production's name.

TYPE: int

SpanLocation didactic-model

SpanLocation(*, file: str, start: int, end: int)

Bases: Model

A name's span in one file.

ATTRIBUTE DESCRIPTION
file

The absolute file path.

TYPE: str

start, end

The byte span.

TYPE: int

Workspace

Workspace(roots: tuple[Path, ...] = ())

The module roots and open buffers of one editor session.

PARAMETER DESCRIPTION
roots

The directories module paths are relative to.

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

Source code in src/quivers/lsp/workspace.py
def __init__(self, roots: tuple[Path, ...] = ()) -> None:
    self.roots = tuple(root.resolve() for root in roots)
    self.overlay: dict[str, str] = {}

set_roots

set_roots(roots: tuple[Path, ...]) -> None

Replace the module roots.

PARAMETER DESCRIPTION
roots

The new roots.

TYPE: tuple[Path, ...]

Source code in src/quivers/lsp/workspace.py
def set_roots(self, roots: tuple[Path, ...]) -> None:
    """Replace the module roots.

    Parameters
    ----------
    roots : tuple[Path, ...]
        The new roots.
    """
    self.roots = tuple(root.resolve() for root in roots)

open

open(file: Path, text: str) -> None

Lay an open buffer over its file.

PARAMETER DESCRIPTION
file

The buffer's file.

TYPE: Path

text

Its current text.

TYPE: str

Source code in src/quivers/lsp/workspace.py
def open(self, file: Path, text: str) -> None:
    """Lay an open buffer over its file.

    Parameters
    ----------
    file : Path
        The buffer's file.
    text : str
        Its current text.
    """
    self.overlay[str(file.resolve())] = text

close

close(file: Path) -> None

Stop laying a closed buffer over its file.

PARAMETER DESCRIPTION
file

The buffer's file.

TYPE: Path

Source code in src/quivers/lsp/workspace.py
def close(self, file: Path) -> None:
    """Stop laying a closed buffer over its file.

    Parameters
    ----------
    file : Path
        The buffer's file.
    """
    self.overlay.pop(str(file.resolve()), None)

text_of

text_of(file: Path) -> str

The current text of a file: its open buffer, or what is on disk.

PARAMETER DESCRIPTION
file

The file.

TYPE: Path

RETURNS DESCRIPTION
str

Its text.

RAISES DESCRIPTION
OSError

If the file is not open and cannot be read.

Source code in src/quivers/lsp/workspace.py
def text_of(self, file: Path) -> str:
    """The current text of a file: its open buffer, or what is on disk.

    Parameters
    ----------
    file : Path
        The file.

    Returns
    -------
    str
        Its text.

    Raises
    ------
    OSError
        If the file is not open and cannot be read.
    """
    resolved = str(file.resolve())
    if resolved in self.overlay:
        return self.overlay[resolved]
    return Path(resolved).read_text(encoding="utf-8")

roots_for

roots_for(file: Path) -> tuple[Path, ...]

The roots a file's module path is relative to.

PARAMETER DESCRIPTION
file

A module file.

TYPE: Path

RETURNS DESCRIPTION
tuple[Path, ...]

The workspace roots when one contains the file; otherwise the file's own directory.

Source code in src/quivers/lsp/workspace.py
def roots_for(self, file: Path) -> tuple[Path, ...]:
    """The roots a file's module path is relative to.

    Parameters
    ----------
    file : Path
        A module file.

    Returns
    -------
    tuple[Path, ...]
        The workspace roots when one contains the file; otherwise the
        file's own directory.
    """
    resolved = file.resolve()
    if any(resolved.is_relative_to(root) for root in self.roots):
        return self.roots
    return (resolved.parent,)

graph_for

graph_for(file: Path) -> ModuleGraph

Load and check the module graph rooted at a file.

PARAMETER DESCRIPTION
file

The root module's file.

TYPE: Path

RETURNS DESCRIPTION
ModuleGraph

The checked graph, open buffers laid over disk.

RAISES DESCRIPTION
ModuleError

If the graph does not load or resolve.

ParseError

If a module does not parse.

Source code in src/quivers/lsp/workspace.py
def graph_for(self, file: Path) -> ModuleGraph:
    """Load and check the module graph rooted at a file.

    Parameters
    ----------
    file : Path
        The root module's file.

    Returns
    -------
    ModuleGraph
        The checked graph, open buffers laid over disk.

    Raises
    ------
    ModuleError
        If the graph does not load or resolve.
    ParseError
        If a module does not parse.
    """
    resolved = file.resolve()
    roots = self.roots_for(resolved)
    files = FileSystemLoader(roots)
    root = ModuleSource(
        identity=SourceModule(path=files.root_path_of(resolved)),
        label=str(resolved),
        text=self.text_of(resolved),
        file=str(resolved),
    )
    loader = ChainLoader(
        (StandardLibraryLoader(), _OverlayLoader(roots, self.overlay), files)
    )
    return load_graph(root, loader)

module_files

module_files() -> tuple[Path, ...]

Every module file below the roots, open buffers included.

RETURNS DESCRIPTION
tuple[Path, ...]

The files, sorted.

Source code in src/quivers/lsp/workspace.py
def module_files(self) -> tuple[Path, ...]:
    """Every module file below the roots, open buffers included.

    Returns
    -------
    tuple[Path, ...]
        The files, sorted.
    """
    found = {
        file.resolve()
        for root in self.roots
        for file in root.rglob("*" + MODULE_SUFFIX)
    }
    found |= {Path(file) for file in self.overlay}
    return tuple(sorted(found))

file_resolutions staticmethod

file_resolutions(graph: ModuleGraph) -> tuple[Resolution, ...]

Every resolution of the root file, its module bodies included.

A module, signature, or functor declared in the file, and a computation with module parameters, resolve their names in scopes of their own (quivers.dsl.modules.elaborate); their resolutions join the file's own. A body whose names do not resolve contributes nothing.

PARAMETER DESCRIPTION
graph

A graph rooted at the file.

TYPE: ModuleGraph

RETURNS DESCRIPTION
tuple[Resolution, ...]

The resolutions, the file's first.

Source code in src/quivers/lsp/workspace.py
@staticmethod
def file_resolutions(graph: ModuleGraph) -> tuple[Resolution, ...]:
    """Every resolution of the root file, its module bodies included.

    A module, signature, or functor declared in the file, and a
    computation with module parameters, resolve their names in scopes
    of their own (`quivers.dsl.modules.elaborate`); their resolutions
    join the file's own. A body whose names do not resolve contributes
    nothing.

    Parameters
    ----------
    graph : ModuleGraph
        A graph rooted at the file.

    Returns
    -------
    tuple[Resolution, ...]
        The resolutions, the file's first.
    """
    found = list(graph.checked[graph.root].resolutions)
    names = graph.loaded[graph.root].names
    if not names.regions:
        return tuple(found)
    system = ModuleSystem(graph, {})
    for region in names.regions:
        try:
            found.extend(
                system.checked(
                    RegionRef(file=graph.root, vid=region.vid)
                ).resolutions
            )
        except ModuleError:
            continue
    return tuple(found)

resolution_at classmethod

resolution_at(graph: ModuleGraph, offset: int) -> Resolution | None

The resolution of the root file whose name spans a byte offset.

PARAMETER DESCRIPTION
graph

A graph rooted at the file.

TYPE: ModuleGraph

offset

A byte offset in the root file.

TYPE: int

RETURNS DESCRIPTION
Resolution | None

The resolution whose own-name segment covers the offset, in the file or in a module body declared in it.

Source code in src/quivers/lsp/workspace.py
@classmethod
def resolution_at(cls, graph: ModuleGraph, offset: int) -> Resolution | None:
    """The resolution of the root file whose name spans a byte offset.

    Parameters
    ----------
    graph : ModuleGraph
        A graph rooted at the file.
    offset : int
        A byte offset in the root file.

    Returns
    -------
    Resolution | None
        The resolution whose own-name segment covers the offset, in the
        file or in a module body declared in it.
    """
    for resolution in cls.file_resolutions(graph):
        if (
            resolution.symbol is not None
            and resolution.name_start <= offset < resolution.name_end
        ):
            return resolution
    return None

declaration_of staticmethod

declaration_of(graph: ModuleGraph, symbol: Symbol) -> SpanLocation | None

Where a module-level name is declared.

PARAMETER DESCRIPTION
graph

A graph containing the declaring module.

TYPE: ModuleGraph

symbol

The name.

TYPE: Symbol

RETURNS DESCRIPTION
SpanLocation | None

The first declaring token, or None when the declaring module has no file.

Source code in src/quivers/lsp/workspace.py
@staticmethod
def declaration_of(graph: ModuleGraph, symbol: Symbol) -> SpanLocation | None:
    """Where a module-level name is declared.

    Parameters
    ----------
    graph : ModuleGraph
        A graph containing the declaring module.
    symbol : Symbol
        The name.

    Returns
    -------
    SpanLocation | None
        The first declaring token, or ``None`` when the declaring
        module has no file.
    """
    checked = graph.checked.get(symbol.module)
    if checked is None:
        return _nested_declaration(graph, symbol)
    if checked.source.file is None:
        return None
    for resolution in checked.resolutions:
        if (
            resolution.role == "declaration"
            and resolution.symbol is not None
            and resolution.symbol.name == symbol.name
        ):
            return SpanLocation(
                file=checked.source.file,
                start=resolution.name_start,
                end=resolution.name_end,
            )
    return None

definition

definition(file: Path, offset: int) -> SpanLocation | None

Where the module-level name at a position is declared.

PARAMETER DESCRIPTION
file

The file.

TYPE: Path

offset

A byte offset in it.

TYPE: int

RETURNS DESCRIPTION
SpanLocation | None

The declaration, or None when the position names no module-level declaration.

RAISES DESCRIPTION
ModuleError

If the file's graph does not load or resolve.

ParseError

If a module does not parse.

Source code in src/quivers/lsp/workspace.py
def definition(self, file: Path, offset: int) -> SpanLocation | None:
    """Where the module-level name at a position is declared.

    Parameters
    ----------
    file : Path
        The file.
    offset : int
        A byte offset in it.

    Returns
    -------
    SpanLocation | None
        The declaration, or ``None`` when the position names no
        module-level declaration.

    Raises
    ------
    ModuleError
        If the file's graph does not load or resolve.
    ParseError
        If a module does not parse.
    """
    graph = self.graph_for(file)
    resolution = self.resolution_at(graph, offset)
    if resolution is None or resolution.symbol is None:
        return None
    return self.declaration_of(graph, resolution.symbol)

symbol_at

symbol_at(file: Path, offset: int) -> Symbol | None

The module-level name at a position.

PARAMETER DESCRIPTION
file

The file.

TYPE: Path

offset

A byte offset in it.

TYPE: int

RETURNS DESCRIPTION
Symbol | None

The name, or None.

RAISES DESCRIPTION
ModuleError

If the file's graph does not load or resolve.

ParseError

If a module does not parse.

Source code in src/quivers/lsp/workspace.py
def symbol_at(self, file: Path, offset: int) -> Symbol | None:
    """The module-level name at a position.

    Parameters
    ----------
    file : Path
        The file.
    offset : int
        A byte offset in it.

    Returns
    -------
    Symbol | None
        The name, or ``None``.

    Raises
    ------
    ModuleError
        If the file's graph does not load or resolve.
    ParseError
        If a module does not parse.
    """
    resolution = self.resolution_at(self.graph_for(file), offset)
    return None if resolution is None else resolution.symbol

references

references(symbol: Symbol) -> tuple[SpanLocation, ...]

Every place in the workspace that spells a module-level name.

Each module file is checked as a root; a file whose graph does not load contributes nothing, since none of its names resolve.

PARAMETER DESCRIPTION
symbol

The name, identified by its declaring module.

TYPE: Symbol

RETURNS DESCRIPTION
tuple[SpanLocation, ...]

The spans of its own-name segment in declarations, references, exports, and import lists, sorted by file and offset.

Source code in src/quivers/lsp/workspace.py
def references(self, symbol: Symbol) -> tuple[SpanLocation, ...]:
    """Every place in the workspace that spells a module-level name.

    Each module file is checked as a root; a file whose graph does not
    load contributes nothing, since none of its names resolve.

    Parameters
    ----------
    symbol : Symbol
        The name, identified by its declaring module.

    Returns
    -------
    tuple[SpanLocation, ...]
        The spans of its own-name segment in declarations, references,
        exports, and import lists, sorted by file and offset.
    """
    found: set[tuple[str, int, int]] = set()
    for file in self.module_files():
        try:
            graph = self.graph_for(file)
        except ModuleError, ParseError, ValueError, OSError:
            continue
        for resolution in self.file_resolutions(graph):
            if resolution.symbol is not None and _same(resolution.symbol, symbol):
                found.add((str(file), resolution.name_start, resolution.name_end))
    return tuple(
        SpanLocation(file=file, start=start, end=end)
        for file, start, end in sorted(found)
    )

fill_candidates

fill_candidates(goal: HoleGoal, module: QiecModule) -> tuple[HoleFill, ...]

The fills of a hole from what is in scope at it.

PARAMETER DESCRIPTION
goal

The goal.

TYPE: HoleGoal

module

The checked module, whose families give the constructors.

TYPE: QiecModule

RETURNS DESCRIPTION
tuple[HoleFill, ...]

The bindings of the goal's type, innermost first; then the goal family's constructors in declaration order; then literals of a builtin goal type.

Source code in src/quivers/lsp/holes.py
def fill_candidates(goal: HoleGoal, module: QiecModule) -> tuple[HoleFill, ...]:
    """The fills of a hole from what is in scope at it.

    Parameters
    ----------
    goal : HoleGoal
        The goal.
    module : QiecModule
        The checked module, whose families give the constructors.

    Returns
    -------
    tuple[HoleFill, ...]
        The bindings of the goal's type, innermost first; then the goal
        family's constructors in declaration order; then literals of a
        builtin goal type.
    """
    texts: list[str] = [
        local.name for local in reversed(goal.bindings) if local.type == goal.type
    ]
    if isinstance(goal.type, TypeApplication):
        family = next(
            (
                item
                for item in module.families
                if item.type_constructor.id == goal.type.constructor.id
            ),
            None,
        )
        if family is not None:
            declared = {item.id: item for item in module.constructors}
            texts += [
                _constructor_fill(goal, declared[identity])
                for identity in family.constructors
                if identity in declared
            ]
    for type_, literals in _LITERALS:
        if goal.type == type_:
            texts += list(literals)
    return tuple(
        HoleFill(title=f"Fill {HOLE_SIGIL}{goal.name} with {text}", text=text)
        for text in dict.fromkeys(texts)
    )

fill_edit

fill_edit(source: str, span: HoleSpan, fill: HoleFill) -> tuple[HoleSpan, str]

The text edit a fill makes.

PARAMETER DESCRIPTION
source

The document.

TYPE: str

span

The hole's span.

TYPE: HoleSpan

fill

The fill.

TYPE: HoleFill

RETURNS DESCRIPTION
tuple[HoleSpan, str]

The span to replace and its replacement. A value hole is replaced by the fill; a declaration hole ?f(..) : T !{e} becomes the define whose body returns the fill.

Source code in src/quivers/lsp/holes.py
def fill_edit(source: str, span: HoleSpan, fill: HoleFill) -> tuple[HoleSpan, str]:
    """The text edit a fill makes.

    Parameters
    ----------
    source : str
        The document.
    span : HoleSpan
        The hole's span.
    fill : HoleFill
        The fill.

    Returns
    -------
    tuple[HoleSpan, str]
        The span to replace and its replacement. A value hole is replaced by
        the fill; a declaration hole ``?f(..) : T !{e}`` becomes the
        ``define`` whose body returns the fill.
    """
    if not span.declaration:
        return span, fill.text
    header = source.split("\n")[span.line][span.start : span.end]
    definition = "define " + header.removeprefix(HOLE_SIGIL)
    if "!{" not in header:
        definition += " !{}"
    return span, f"{definition} =\n    return {fill.text}"

goal_at

goal_at(module: QiecModule, source: str, line: int, column: int) -> HoleGoal | None

The goal of the hole under a position.

PARAMETER DESCRIPTION
module

The checked module.

TYPE: QiecModule

source

The document.

TYPE: str

line

The 0-based line.

TYPE: int

column

The 0-based character column.

TYPE: int

RETURNS DESCRIPTION
HoleGoal or None

The goal whose hole covers the position, if any.

Source code in src/quivers/lsp/holes.py
def goal_at(module: QiecModule, source: str, line: int, column: int) -> HoleGoal | None:
    """The goal of the hole under a position.

    Parameters
    ----------
    module : QiecModule
        The checked module.
    source : str
        The document.
    line : int
        The 0-based line.
    column : int
        The 0-based character column.

    Returns
    -------
    HoleGoal or None
        The goal whose hole covers the position, if any.
    """
    for goal in goals_of(module):
        span = hole_span(source, goal)
        if span is not None and span.line == line and span.start <= column <= span.end:
            return goal
    return None

goals_of

goals_of(module: QiecModule) -> tuple[HoleGoal, ...]

The goals of a checked module's value holes, computed once per module.

PARAMETER DESCRIPTION
module

The checked module.

TYPE: QiecModule

RETURNS DESCRIPTION
tuple[HoleGoal, ...]

One goal per hole occurrence.

Source code in src/quivers/lsp/holes.py
def goals_of(module: QiecModule) -> tuple[HoleGoal, ...]:
    """The goals of a checked module's value holes, computed once per module.

    Parameters
    ----------
    module : QiecModule
        The checked module.

    Returns
    -------
    tuple[HoleGoal, ...]
        One goal per hole occurrence.
    """
    known = _GOALS.get(module)
    if known is None:
        known = hole_goals(module)
        _GOALS[module] = known
    return known

hole_diagnostics

hole_diagnostics(module: QiecModule) -> list[Diagnostic]

Publish each hole's goal as an information diagnostic.

PARAMETER DESCRIPTION
module

The checked module.

TYPE: QiecModule

RETURNS DESCRIPTION
list[Diagnostic]

One qiec-hole diagnostic per hole, at the hole.

Source code in src/quivers/lsp/holes.py
def hole_diagnostics(module: QiecModule) -> list[Diagnostic]:
    """Publish each hole's goal as an information diagnostic.

    Parameters
    ----------
    module : QiecModule
        The checked module.

    Returns
    -------
    list[Diagnostic]
        One ``qiec-hole`` diagnostic per hole, at the hole.
    """
    return [
        Diagnostic(
            message=f"goal {goal.render()}",
            severity="info",
            line=goal.origin.line or 0,
            col=goal.origin.column or 0,
            code="qiec-hole",
        )
        for goal in goals_of(module)
    ]

hole_span

hole_span(source: str, goal: HoleGoal) -> HoleSpan | None

Find where a goal's hole is written in its document.

PARAMETER DESCRIPTION
source

The document the module was checked from.

TYPE: str

goal

The goal.

TYPE: HoleGoal

RETURNS DESCRIPTION
HoleSpan or None

The span of the hole (?x or ?x : T), or of the header of a declaration hole; None when the hole lies in another file or the document no longer parses.

Source code in src/quivers/lsp/holes.py
def hole_span(source: str, goal: HoleGoal) -> HoleSpan | None:
    """Find where a goal's hole is written in its document.

    Parameters
    ----------
    source : str
        The document the module was checked from.
    goal : HoleGoal
        The goal.

    Returns
    -------
    HoleSpan or None
        The span of the hole (``?x`` or ``?x : T``), or of the header of a
        declaration hole; None when the hole lies in another file or the
        document no longer parses.
    """
    origin = goal.origin
    if origin.line is None or origin.column is None:
        return None
    try:
        tree = parse_tree(source)
    except ParseError:
        return None
    for vid in tree.vertices:
        kind = tree.kind(vid)
        if kind not in ("let_hole", "typed_hole_decl"):
            continue
        if tree.line_col(vid) != (origin.line, origin.column):
            continue
        text = tree.text(vid).rstrip("\n").split("\n")[0].rstrip()
        line = origin.line - 1
        start = _character_column(source, line, origin.column)
        return HoleSpan(
            line=line,
            start=start,
            end=start + len(text),
            declaration=kind == "typed_hole_decl",
        )
    return None

render_goal

render_goal(goal: HoleGoal) -> str

Render a goal for a hover pane.

PARAMETER DESCRIPTION
goal

The goal.

TYPE: HoleGoal

RETURNS DESCRIPTION
str

Markdown: the hole and its type, then each binding in scope.

Source code in src/quivers/lsp/holes.py
def render_goal(goal: HoleGoal) -> str:
    """Render a goal for a hover pane.

    Parameters
    ----------
    goal : HoleGoal
        The goal.

    Returns
    -------
    str
        Markdown: the hole and its type, then each binding in scope.
    """
    lines = [
        f"**Goal** `{HOLE_SIGIL}{goal.name} : {render_static(goal.type)}`",
        "",
        f"in `{goal.declaration}`",
    ]
    if goal.bindings:
        lines += ["", "**In scope**", ""]
        lines += [
            f"- `{local.name} : {render_static(local.type)}`" for local in goal.bindings
        ]
    else:
        lines += ["", "Nothing is in scope."]
    return "\n".join(lines)

notation_definition

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

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

PARAMETER DESCRIPTION
module

The document's program.

TYPE: Module

source

The document's text.

TYPE: str

line

The 0-based line.

TYPE: int

col

The 0-based character column.

TYPE: int

file

The document.

TYPE: str

source_map

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

TYPE: SourceMap | None DEFAULT: None

RETURNS DESCRIPTION
NotationTarget | None

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

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

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

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

notation_hover

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

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

PARAMETER DESCRIPTION
module

The document's program.

TYPE: Module

source

The document's text.

TYPE: str

line

The 0-based line.

TYPE: int

col

The 0-based character column.

TYPE: int

file

The document, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
str | None

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

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

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

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

quotation_at

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

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

PARAMETER DESCRIPTION
module

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

TYPE: Module

source

The document's text.

TYPE: str

line

The 0-based line.

TYPE: int

col

The 0-based character column.

TYPE: int

RETURNS DESCRIPTION
tuple[Quotation, int] | None

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

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

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

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

build_server

build_server(*, target: str | None = None) -> LanguageServer

Build a QVR language server with every feature registered.

PARAMETER DESCRIPTION
target

A transpile target whose missing capabilities are published as qiec:capability:* diagnostics; None disables them. A client may change it later through workspace/didChangeConfiguration.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
LanguageServer

The configured pygls server, ready for start_io or start_tcp.

Source code in src/quivers/lsp/server.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
def build_server(*, target: str | None = None) -> LanguageServer:
    """Build a QVR language server with every feature registered.

    Parameters
    ----------
    target : str or None
        A transpile target whose missing capabilities are published as
        ``qiec:capability:*`` diagnostics; ``None`` disables them. A
        client may change it later through
        ``workspace/didChangeConfiguration``.

    Returns
    -------
    LanguageServer
        The configured pygls server, ready for ``start_io`` or
        ``start_tcp``.
    """
    server = LanguageServer(
        name=SERVER_NAME, version=SERVER_VERSION, protocol_cls=_QvrProtocol
    )
    docs: dict[str, DocumentState] = {}
    selected_target = target
    workspace = Workspace()

    def sync_workspace(ls: LanguageServer, doc: DocumentState) -> None:
        workspace.set_roots(_workspace_roots(ls))
        file = file_of_uri(doc.uri)
        if file is not None:
            workspace.open(file, doc.source)

    # ----- lifecycle ----------------------------------------------------

    @server.feature(lsp.TEXT_DOCUMENT_DID_OPEN)
    def _did_open(ls: LanguageServer, params: lsp.DidOpenTextDocumentParams) -> None:
        doc = DocumentState(
            uri=params.text_document.uri, target=selected_target, workspace=workspace
        )
        doc.source = params.text_document.text
        sync_workspace(ls, doc)
        doc.update(
            source=params.text_document.text,
            version=params.text_document.version,
        )
        docs[doc.uri] = doc
        _publish(ls, doc)

    @server.feature(lsp.TEXT_DOCUMENT_DID_CHANGE)
    def _did_change(
        ls: LanguageServer, params: lsp.DidChangeTextDocumentParams
    ) -> None:
        uri = params.text_document.uri
        doc = docs.get(uri)
        if doc is None:
            return
        # Apply incremental changes if present; full-replace otherwise.
        for change in params.content_changes:
            if isinstance(change, lsp.TextDocumentContentChangePartial):
                doc.source = _apply_partial(doc.source, change)
            else:
                doc.source = change.text
        sync_workspace(ls, doc)
        doc.update(source=doc.source, version=params.text_document.version)
        _publish(ls, doc)

    @server.feature(lsp.TEXT_DOCUMENT_DID_SAVE)
    def _did_save(ls: LanguageServer, params: lsp.DidSaveTextDocumentParams) -> None:
        doc = docs.get(params.text_document.uri)
        if doc is None:
            return
        if params.text is not None:
            doc.update(source=params.text, version=doc.version)
        _publish(ls, doc)

    @server.feature(lsp.TEXT_DOCUMENT_DID_CLOSE)
    def _did_close(ls: LanguageServer, params: lsp.DidCloseTextDocumentParams) -> None:
        docs.pop(params.text_document.uri, None)
        file = file_of_uri(params.text_document.uri)
        if file is not None:
            workspace.close(file)
        ls.text_document_publish_diagnostics(
            lsp.PublishDiagnosticsParams(uri=params.text_document.uri, diagnostics=[])
        )

    @server.feature(lsp.WORKSPACE_DID_CHANGE_CONFIGURATION)
    def _did_change_configuration(
        ls: LanguageServer, params: lsp.DidChangeConfigurationParams
    ) -> None:
        """Refresh target-capability diagnostics for every open document.

        Clients may send either the VS Code-shaped
        ``{qvr: {transpileTarget: ...}}`` object or the section value
        ``{transpileTarget: ...}``. An empty string disables target-specific
        diagnostics. Settings unrelated to the target leave it unchanged.
        """

        nonlocal selected_target
        configured = _target_from_settings(params.settings)
        if configured is _TARGET_UNCHANGED:
            return
        selected_target = cast(str | None, configured)
        for doc in docs.values():
            doc.retarget(selected_target)
            _publish(ls, doc)

    # ----- semantic tokens ---------------------------------------------

    @server.feature(
        lsp.TEXT_DOCUMENT_SEMANTIC_TOKENS_FULL,
        lsp.SemanticTokensLegend(
            token_types=list(SEMANTIC_TOKEN_TYPES),
            token_modifiers=list(SEMANTIC_TOKEN_MODIFIERS),
        ),
    )
    def _semantic_tokens(
        _ls: LanguageServer, params: lsp.SemanticTokensParams
    ) -> lsp.SemanticTokens:
        doc = docs.get(params.text_document.uri)
        if doc is None:
            return lsp.SemanticTokens(data=[])
        env_kinds = _env_kinds_for(doc)
        data = to_semantic_token_data(doc.source, env_kinds=env_kinds)
        return lsp.SemanticTokens(data=data)

    # ----- hover --------------------------------------------------------

    @server.feature(lsp.TEXT_DOCUMENT_HOVER)
    def _hover(_ls: LanguageServer, params: lsp.HoverParams) -> lsp.Hover | None:
        doc = docs.get(params.text_document.uri)
        if doc is None:
            return None
        position = _python_position(doc.source, params.position)
        quotation = notation_hover(
            doc.flat_module or doc.module,
            doc.source,
            position.line,
            position.character,
            file=doc.uri,
        )
        if quotation is not None:
            return lsp.Hover(
                contents=lsp.MarkupContent(
                    kind=lsp.MarkupKind.Markdown, value=quotation
                )
            )
        if doc.qiec_module is not None:
            goal = goal_at(
                doc.qiec_module, doc.source, position.line, position.character
            )
            if goal is not None:
                return lsp.Hover(
                    contents=lsp.MarkupContent(
                        kind=lsp.MarkupKind.Markdown, value=render_goal(goal)
                    )
                )
        scoped = _scoped_ref_at(doc, position.line, position.character)
        if scoped is not None:
            return lsp.Hover(
                contents=lsp.MarkupContent(
                    kind=lsp.MarkupKind.Markdown,
                    value=_render_scoped_hover(doc, scoped),
                )
            )
        name = doc.name_at_position(position.line, position.character)
        if name is None:
            return None
        body = _render_hover(
            doc,
            name,
            line=position.line,
            col=position.character,
        )
        if body is None:
            body = module_language_hover(workspace, doc, position)
        if body is None:
            return None
        return lsp.Hover(
            contents=lsp.MarkupContent(kind=lsp.MarkupKind.Markdown, value=body)
        )

    # ----- code actions: fill a typed hole -------------------------------

    @server.feature(
        lsp.TEXT_DOCUMENT_CODE_ACTION,
        lsp.CodeActionOptions(code_action_kinds=[lsp.CodeActionKind.QuickFix]),
    )
    def _code_action(
        _ls: LanguageServer, params: lsp.CodeActionParams
    ) -> list[lsp.CodeAction] | None:
        doc = docs.get(params.text_document.uri)
        if doc is None or doc.qiec_module is None:
            return None
        position = _python_position(doc.source, params.range.start)
        goal = goal_at(doc.qiec_module, doc.source, position.line, position.character)
        if goal is None:
            return None
        span = hole_span(doc.source, goal)
        if span is None:
            return None
        actions: list[lsp.CodeAction] = []
        for fill in fill_candidates(goal, doc.qiec_module):
            target, text = fill_edit(doc.source, span, fill)
            edit = lsp.TextEdit(
                range=lsp.Range(
                    start=_wire_position(doc.source, target.line, target.start),
                    end=_wire_position(doc.source, target.line, target.end),
                ),
                new_text=text,
            )
            actions.append(
                lsp.CodeAction(
                    title=fill.title,
                    kind=lsp.CodeActionKind.QuickFix,
                    edit=lsp.WorkspaceEdit(changes={doc.uri: [edit]}),
                )
            )
        return actions

    # ----- definition / references / documentSymbol --------------------

    @server.feature(lsp.TEXT_DOCUMENT_DEFINITION)
    def _definition(
        _ls: LanguageServer, params: lsp.DefinitionParams
    ) -> list[lsp.Location] | None:
        doc = docs.get(params.text_document.uri)
        if doc is None:
            return None
        position = _python_position(doc.source, params.position)
        production = notation_definition(
            doc.flat_module or doc.module,
            doc.source,
            position.line,
            position.character,
            file=doc.uri,
            source_map=doc.source_map,
        )
        if production is not None:
            return [_notation_location(doc, production)]
        scoped = _scoped_ref_at(doc, position.line, position.character)
        if scoped is not None:
            target = _scoped_ref_position(doc, scoped)
            if target is None:
                return None
            line, col = target
            return [
                lsp.Location(
                    uri=doc.uri,
                    range=lsp.Range(
                        start=_wire_position(doc.source, line, col),
                        end=_wire_position(doc.source, line, col + len(scoped.name)),
                    ),
                )
            ]
        name = doc.name_at_position(position.line, position.character)
        if name is None:
            return None
        decl = doc.find_decl(
            name,
            line=position.line,
            col=position.character,
        )
        if decl is None:
            generated = _spliced_binding_at(
                doc, name, line=position.line, col=position.character
            )
            if generated is None:
                return None
            splice, _ = generated
            line = splice.line - 1
            source_line = doc.source.splitlines()[line]
            col = len(source_line.encode("utf-8")[: splice.col].decode("utf-8"))
            name = f"${splice.generator}"
        else:
            line, col = _name_position(doc, decl, name)
        return [
            lsp.Location(
                uri=doc.uri,
                range=lsp.Range(
                    start=_wire_position(doc.source, line, col),
                    end=_wire_position(doc.source, line, col + len(name)),
                ),
            )
        ]

    @server.feature(lsp.TEXT_DOCUMENT_REFERENCES)
    def _references(
        _ls: LanguageServer, params: lsp.ReferenceParams
    ) -> list[lsp.Location] | None:
        doc = docs.get(params.text_document.uri)
        if doc is None:
            return None
        position = _python_position(doc.source, params.position)
        name = doc.name_at_position(position.line, position.character)
        if name is None:
            return None
        return list(
            _find_references(
                doc,
                name,
                line=position.line,
                col=position.character,
            )
        )

    @server.feature(lsp.TEXT_DOCUMENT_PREPARE_RENAME)
    def _prepare_rename(
        _ls: LanguageServer, params: lsp.PrepareRenameParams
    ) -> lsp.PrepareRenameResult_Type1 | None:
        doc = docs.get(params.text_document.uri)
        if doc is None:
            return None
        position = _python_position(doc.source, params.position)
        symbol = workspace_symbol(workspace, doc, position)
        if symbol is not None and workspace.roots:
            return _prepare_symbol_rename(doc, position, symbol)
        name = doc.name_at_position(position.line, position.character)
        if name is None:
            return None
        if _renameable_declaration(doc, name, position) is None:
            return None
        line, col = position.line, position.character
        text = doc.source.splitlines()[line]
        start = text.rfind(name, 0, col + len(name))
        return lsp.PrepareRenameResult_Type1(
            range=lsp.Range(
                start=_wire_position(doc.source, line, start),
                end=_wire_position(doc.source, line, start + len(name)),
            ),
            placeholder=name,
        )

    @server.feature(lsp.TEXT_DOCUMENT_RENAME)
    def _rename(
        _ls: LanguageServer, params: lsp.RenameParams
    ) -> lsp.WorkspaceEdit | None:
        doc = docs.get(params.text_document.uri)
        if doc is None:
            return None
        position = _python_position(doc.source, params.position)
        if not params.new_name.isidentifier():
            return None
        across = cross_module_rename(workspace, doc, position, params.new_name)
        if across is not None:
            return across
        name = doc.name_at_position(position.line, position.character)
        if name is None:
            return None
        if _renameable_declaration(doc, name, position) is None:
            return None
        puns = _binding_tokens(doc.source).puns
        edits = [
            lsp.TextEdit(
                range=location.range,
                # A pun names the label it binds and the binding it reads;
                # the rename keeps the label and changes what it reads.
                new_text=(
                    f"{name} = {params.new_name}"
                    if _byte_offset(
                        doc.source,
                        location.range.start.line,
                        _python_position(doc.source, location.range.start).character,
                    )
                    in puns
                    else params.new_name
                ),
            )
            for location in _find_references(
                doc,
                name,
                line=position.line,
                col=position.character,
            )
        ]
        if not edits:
            return None
        return lsp.WorkspaceEdit(changes={doc.uri: edits})

    @server.feature(lsp.TEXT_DOCUMENT_DOCUMENT_SYMBOL)
    def _symbols(
        _ls: LanguageServer, params: lsp.DocumentSymbolParams
    ) -> list[lsp.DocumentSymbol]:
        doc = docs.get(params.text_document.uri)
        if doc is None:
            return []
        return _statement_symbols(doc, doc.module.statements)

    # ----- completion ---------------------------------------------------

    @server.feature(
        lsp.TEXT_DOCUMENT_COMPLETION,
        lsp.CompletionOptions(trigger_characters=[":", " ", "."]),
    )
    def _completion(
        _ls: LanguageServer, params: lsp.CompletionParams
    ) -> lsp.CompletionList:
        doc = docs.get(params.text_document.uri)
        if doc is None:
            return lsp.CompletionList(is_incomplete=False, items=[])
        position = _python_position(doc.source, params.position)
        session = ReplSession()
        session._module = doc.module  # noqa: SLF001
        session._compiler = doc.compiler  # noqa: SLF001
        session._qiec_module = doc.qiec_module  # noqa: SLF001
        session._env = doc.env  # noqa: SLF001
        session._generated_declarations = doc.generated_declarations  # noqa: SLF001
        prefix = _prefix_at(doc.source, position.line, position.character)
        items = _qiec_local_completion_items(
            doc,
            prefix,
            line=position.line,
            col=position.character,
        )
        items.extend(
            _model_operation_completion_items(
                doc.source, position.line, position.character
            )
        )
        local_names = {item.label for item in items}
        items.extend(
            lsp.CompletionItem(
                label=completion.text,
                kind=_completion_kind(completion.kind),
                detail=completion.detail,
            )
            for completion in all_completions(session, prefix)
            if completion.text not in local_names
        )
        return lsp.CompletionList(is_incomplete=False, items=items)

    # ----- formatting ---------------------------------------------------

    @server.feature(lsp.TEXT_DOCUMENT_FORMATTING)
    def _formatting(
        _ls: LanguageServer, params: lsp.DocumentFormattingParams
    ) -> list[lsp.TextEdit] | None:
        doc = docs.get(params.text_document.uri)
        return _format_document(doc) if doc is not None else None

    # The pygls feature decorator registers each handler with the
    # server, but the resulting name is never referenced from this
    # function's local scope, so the linter flags it as unused. The
    # tuple below names every handler explicitly to make the lifetime
    # contract legible to a reader and to the type checker.
    _registered_handlers = (
        _did_open,
        _did_change,
        _did_save,
        _did_close,
        _did_change_configuration,
        _semantic_tokens,
        _hover,
        _code_action,
        _definition,
        _references,
        _prepare_rename,
        _rename,
        _symbols,
        _completion,
        _formatting,
    )
    del _registered_handlers

    return server

byte_offset

byte_offset(text: str, line: int, column: int) -> int

The byte offset of a line and character column.

PARAMETER DESCRIPTION
text

The file's text.

TYPE: str

line

A 0-based line.

TYPE: int

column

A 0-based character column.

TYPE: int

RETURNS DESCRIPTION
int

The UTF-8 byte offset.

Source code in src/quivers/lsp/workspace.py
def byte_offset(text: str, line: int, column: int) -> int:
    """The byte offset of a line and character column.

    Parameters
    ----------
    text : str
        The file's text.
    line : int
        A 0-based line.
    column : int
        A 0-based character column.

    Returns
    -------
    int
        The UTF-8 byte offset.
    """
    lines = text.split("\n")
    prefix = "\n".join(lines[:line])
    offset = len(prefix.encode("utf-8")) + (1 if line > 0 else 0)
    return (
        offset + len(lines[line][:column].encode("utf-8"))
        if line < len(lines)
        else offset
    )

file_of_uri

file_of_uri(uri: str) -> Path | None

The file a file:// document URI names.

PARAMETER DESCRIPTION
uri

A document URI.

TYPE: str

RETURNS DESCRIPTION
Path | None

The file, or None for a URI of another scheme.

Source code in src/quivers/lsp/workspace.py
def file_of_uri(uri: str) -> Path | None:
    """The file a ``file://`` document URI names.

    Parameters
    ----------
    uri : str
        A document URI.

    Returns
    -------
    Path | None
        The file, or ``None`` for a URI of another scheme.
    """
    parsed = urlparse(uri)
    if parsed.scheme != "file":
        return None
    return Path(unquote(parsed.path))

line_column

line_column(text: str, offset: int) -> tuple[int, int]

The 0-based line and character column of a byte offset.

PARAMETER DESCRIPTION
text

The file's text.

TYPE: str

offset

A UTF-8 byte offset.

TYPE: int

RETURNS DESCRIPTION
tuple[int, int]

The line and the character column.

Source code in src/quivers/lsp/workspace.py
def line_column(text: str, offset: int) -> tuple[int, int]:
    """The 0-based line and character column of a byte offset.

    Parameters
    ----------
    text : str
        The file's text.
    offset : int
        A UTF-8 byte offset.

    Returns
    -------
    tuple[int, int]
        The line and the character column.
    """
    before = text.encode("utf-8")[:offset].decode("utf-8")
    line = before.count("\n")
    return line, len(before) - (before.rfind("\n") + 1)

kernel

Jupyter kernel for QVR.

Two console-script entry points:

  • qvr kernel install registers the kernelspec.
  • qvr kernel run is invoked by Jupyter once a notebook starts.

The kernel reuses ReplSession so notebook cells behave exactly like the REPL: leading : runs a meta command; bare cells parse first as statements (appended to the session's module) and fall back to type-printing.

KERNELSPEC module-attribute

KERNELSPEC = {'argv': [sys.executable, '-m', 'quivers.kernel', '_run_f', '{connection_file}'], 'display_name': 'quivers', 'language': 'qvr', 'interrupt_mode': 'signal', 'metadata': {'debugger': False}}

The kernel.json document install_kernelspec registers: it launches the kernel with the running interpreter and names the language qvr.

QuiversKernel

QuiversKernel(**kwargs: Any)

Bases: Kernel

A Jupyter kernel that evaluates QVR cells in a ReplSession.

Each line of a cell is dispatched to the session as the REPL would dispatch it, so a leading : runs a meta-command and other input is elaborated against the session's module. Jupyter constructs the kernel; install_kernelspec registers it.

PARAMETER DESCRIPTION
**kwargs

Keyword arguments forwarded to ipykernel.kernelbase.Kernel.

TYPE: Any DEFAULT: {}

Source code in src/quivers/kernel/quivers_kernel.py
def __init__(self, **kwargs: Any) -> None:
    super().__init__(**kwargs)
    self.repl = ReplSession()

do_execute

do_execute(code: str, silent: bool, store_history: bool = True, user_expressions: dict[str, Any] | None = None, allow_stdin: bool = False, *, cell_id: str | None = None) -> dict[str, Any]

Dispatch each chunk of a cell to the session.

A :quit chunk ends the cell: the chunks after it are not dispatched, and the kernel stays up, since a kernel is shut down by its front end. Unless silent, a note on standard error says so.

PARAMETER DESCRIPTION
code

The cell.

TYPE: str

silent

Whether to suppress the cell's output streams.

TYPE: bool

store_history

Unused; part of the ipykernel signature.

TYPE: bool DEFAULT: True

user_expressions

Unused; part of the ipykernel signature.

TYPE: dict[str, Any] | None DEFAULT: None

allow_stdin

Unused; part of the ipykernel signature.

TYPE: bool DEFAULT: False

cell_id

Unused; part of the ipykernel signature.

TYPE: str | None DEFAULT: None

RETURNS DESCRIPTION
dict[str, Any]

The execute reply: "error" status if any chunk reported an error diagnostic or failed response, "ok" otherwise. Execution stops at the first failed chunk, including in silent mode.

Source code in src/quivers/kernel/quivers_kernel.py
def do_execute(
    self,
    code: str,
    silent: bool,
    store_history: bool = True,
    user_expressions: dict[str, Any] | None = None,
    allow_stdin: bool = False,
    *,
    cell_id: str | None = None,
) -> dict[str, Any]:
    """Dispatch each chunk of a cell to the session.

    A ``:quit`` chunk ends the cell: the chunks after it are not
    dispatched, and the kernel stays up, since a kernel is shut down
    by its front end. Unless ``silent``, a note on standard error
    says so.

    Parameters
    ----------
    code : str
        The cell.
    silent : bool
        Whether to suppress the cell's output streams.
    store_history : bool
        Unused; part of the ipykernel signature.
    user_expressions : dict[str, Any] | None
        Unused; part of the ipykernel signature.
    allow_stdin : bool
        Unused; part of the ipykernel signature.
    cell_id : str | None
        Unused; part of the ipykernel signature.

    Returns
    -------
    dict[str, Any]
        The execute reply: ``"error"`` status if any chunk reported
        an error diagnostic or failed response, ``"ok"`` otherwise.
        Execution stops at the first failed chunk, including in silent mode.
    """
    del store_history, user_expressions, allow_stdin, cell_id
    failure: dict[str, Any] | None = None
    for response in _cell_responses(self.repl, _split_cell(code)):
        if response.body == "__quit__":
            if not silent:
                self.send_response(
                    self.iopub_socket,
                    "stream",
                    {
                        "name": "stderr",
                        "text": (
                            ":quit ends this cell; shut the kernel down "
                            "from the front end\n"
                        ),
                    },
                )
            break
        errors = [d for d in response.diagnostics if d.severity == "error"]
        if not response.ok or errors:
            failure = {
                "ename": errors[0].code or "QvrError" if errors else "QvrError",
                "evalue": "\n".join(d.message for d in errors) or response.body,
                "traceback": [
                    f"{d.code or 'QvrError'}: {d.message}" for d in errors
                ]
                or [response.body],
            }
            if not silent:
                self.send_response(self.iopub_socket, "error", failure)
            break
        if not silent:
            if response.body:
                stream = "stderr" if not response.ok else "stdout"
                self.send_response(
                    self.iopub_socket,
                    "stream",
                    {"name": stream, "text": response.body + "\n"},
                )
            for diag in response.diagnostics:
                self.send_response(
                    self.iopub_socket,
                    "stream",
                    {
                        "name": "stderr",
                        "text": f"{diag.severity}[{diag.code}]: {diag.message}\n",
                    },
                )
    if failure is not None:
        return {
            "status": "error",
            "execution_count": self.execution_count,
            **failure,
        }
    return {
        "status": "ok",
        "execution_count": self.execution_count,
        "payload": [],
        "user_expressions": {},
    }

install_kernelspec

install_kernelspec(*, user: bool = True, prefix: str | None = None) -> Path

Register the QVR kernelspec with Jupyter.

PARAMETER DESCRIPTION
user

Install into the per-user kernel directory rather than the system one.

TYPE: bool DEFAULT: True

prefix

An explicit Jupyter prefix to install under, as PREFIX/share/jupyter/kernels; None uses Jupyter's default location.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
Path

The directory the kernelspec was installed into.

RAISES DESCRIPTION
ImportError

When jupyter_client is not installed.

Source code in src/quivers/kernel/install.py
def install_kernelspec(*, user: bool = True, prefix: str | None = None) -> Path:
    """Register the QVR kernelspec with Jupyter.

    Parameters
    ----------
    user : bool
        Install into the per-user kernel directory rather than the
        system one.
    prefix : str or None
        An explicit Jupyter prefix to install under, as
        ``PREFIX/share/jupyter/kernels``; ``None`` uses Jupyter's
        default location.

    Returns
    -------
    Path
        The directory the kernelspec was installed into.

    Raises
    ------
    ImportError
        When ``jupyter_client`` is not installed.
    """
    if not _JUPYTER_AVAILABLE:
        raise ModuleNotFoundError(
            "Kernel installation requires quivers[repl]", name="jupyter_client"
        )

    with tempfile.TemporaryDirectory() as tmp:
        tmp_path = Path(tmp)
        (tmp_path / "kernel.json").write_text(
            json.dumps(KERNELSPEC, indent=2), encoding="utf-8"
        )
        mgr = KernelSpecManager()
        dest = mgr.install_kernel_spec(
            str(tmp_path),
            kernel_name="quivers",
            user=user,
            prefix=prefix,
        )
    return Path(dest)

__getattr__

__getattr__(name: str) -> type[QuiversKernel]

Resolve the kernel class when its optional runtime is requested.

PARAMETER DESCRIPTION
name

The requested public name.

TYPE: str

RETURNS DESCRIPTION
type[QuiversKernel]

The Jupyter kernel implementation.

RAISES DESCRIPTION
AttributeError

If the name is not the kernel class.

ModuleNotFoundError

If the Jupyter kernel dependencies are absent.

Source code in src/quivers/kernel/__init__.py
def __getattr__(name: str) -> type[QuiversKernel]:
    """Resolve the kernel class when its optional runtime is requested.

    Parameters
    ----------
    name : str
        The requested public name.

    Returns
    -------
    type[QuiversKernel]
        The Jupyter kernel implementation.

    Raises
    ------
    AttributeError
        If the name is not the kernel class.
    ModuleNotFoundError
        If the Jupyter kernel dependencies are absent.
    """
    if name != "QuiversKernel":
        raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
    value: type[QuiversKernel] = importlib.import_module(
        "quivers.kernel.quivers_kernel"
    ).QuiversKernel
    globals()[name] = value
    return value