Skip to content

AST Nodes

Abstract syntax tree node definitions for the QVR DSL.

ast_nodes

AST node definitions for the quivers DSL ().

The AST is a direct representation of the parsed .qvr source. Each node carries source-location info for error reporting. Recursive sums use dx.TaggedUnion with a kind discriminator: variants subclass their sum's root and pin kind to a Literal[...] value.

This package's submodules group the node families:

  • ._shared for shared helpers (AxisSpec, CompositionLevel, the option-value tagged union)
  • .types for type expressions
  • .let_expressions for let-arith expressions
  • .expressions for value (morphism) expressions
  • .program_steps for monadic program steps
  • .structural for structural-compression helpers
  • .declarations for top-level statements (sixteen variants)
  • .module for the file-level Module container

Every public class is re-exported here so from quivers.dsl.ast_nodes import X keeps working.

QiecValue module-attribute

QiecValue = LetExprNode

A QIEC value, which is the shared pure-expression tree.

Variables, literals, operators, tuples, and builtin applications are the same nodes a program let step uses; constructor application joins that tree, so there is one value language rather than two isomorphic ones.

CompositionLevel

CompositionLevel = Literal['algebra', 'semigroupoid', 'bilinear_form', 'rule']

Algebraic level the file declares for its composition rule.

The four levels correspond to the quivers.core.algebras.CompositionRule-hierarchy:

  • "algebra" requires a full Algebra (unit, zero, meet, negate, identity, dagger, cup/cap).
  • "semigroupoid" requires a Semigroupoid (associative tensor_op, no identity required).
  • "bilinear_form" requires a BilinearForm (no associativity promise).
  • "composition_rule" is permissive: any CompositionRule is accepted.

MorphismRole

MorphismRole = Literal['latent', 'observed', 'kernel', 'embed', 'discretize', 'let']

Role attribute on a morphism declaration.

latent (default learnable point estimate), observed (fixed structural input), kernel (parametric Markov kernel with a family prior), embed (FinSet -> ContinuousSpace boundary), discretize (ContinuousSpace -> FinSet boundary), let (deterministic let-bound morphism). Optional; when the option block carries no role, the morphism is a kernel. Every other role is explicit.

LetBinaryOperator

LetBinaryOperator = Literal['+', '-', '*', '/', '%', '==', '!=', '<', '<=', '>', '>=', '&&', '||']

The operator of a binary let expression: arithmetic, comparison, or boolean.

QiecHandlerImplementation

QiecHandlerImplementation = Literal['authored', 'foreign']

Whether a handler's clause bodies are written in source.

An "authored" handler carries a body for every clause; a "foreign" handler may give clause signatures without bodies, which the target runtime supplies.

QiecResumptionGrade

QiecResumptionGrade = Literal['0', 'aff', '1', 'omega']

How many times an operation clause may resume its continuation.

"0" never resumes, "aff" resumes at most once, "1" resumes exactly once, and "omega" resumes any number of times.

QiecStaticArgument

QiecStaticArgument = QiecTypeExpr | QiecIndexLiteral

A static argument: a type or effect written as type syntax, or an index literal.

AxisSpec didactic-model

AxisSpec(*, over: tuple[str, ...], iid_over: tuple[str, ...] = (), line: int = 0, col: int = 0)

Bases: Model

Axis-role specification on a distribution clause.

Surface form: over <axes> [iid over <axes>].

over names the event axes, the axes on which the family's joint structure (an MVN covariance, a MatrixNormal Kronecker pair, a GP kernel) lives. The axis count must match the family's declared event rank; the positional ordering corresponds positionally to the family's event-axis ordering.

iid_over is an optional readability assertion naming the batch axes (the complement of over in the surrounding morphism's type signature). Inconsistency with the type signature or with over is a compile-time error.

Axis names resolve against the named factors of the surrounding morphism's dom/cod. The reserved tokens dom and cod are legal shortcuts only when the corresponding side is a single unfactored object.

BundleDecl didactic-model

BundleDecl(*, name: str, rules: tuple[str, ...], docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['bundle_decl'] = 'bundle_decl')

Bases: Statement

bundle NAME : [rule1, rule2, ...] first-class schema bundle.

Binds NAME to a tuple of schema references; parser(rules=NAME) and chart_fold(binary=NAME, ...) resolve the bundle by name and splice its members into the rule list.

CategoryDecl didactic-model

CategoryDecl(*, names: tuple[str, ...], docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['category_decl'] = 'category_decl')

Bases: Statement

category NAME, NAME, ... declaration.

CompositionDecl didactic-model

CompositionDecl(*, name: str, level: CompositionLevel | None = None, body: tuple[CompositionRuleEntry, ...] = (), docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['composition_decl'] = 'composition_decl')

Bases: Statement

composition NAME [level=LEVEL] [: body] declaration.

level records which algebraic level the option block advertises; the optional body defines the rule's operations inline.

CompositionRuleEntry didactic-model

CompositionRuleEntry(*, key: str, params: tuple[str, ...] = (), body: LetExprNode, line: int = 0, col: int = 0)

Bases: Model

One entry of a composition body block.

Function-valued entries (tensor_op, join, negation, meet) declare a lambda over named parameters; value-valued entries (unit, zero) declare a numeric literal. The params tuple is empty for value-valued entries.

ContractionDecl didactic-model

ContractionDecl(*, name: str, inputs: tuple[ContractionInput, ...], domain: ObjectExpr, codomain: ObjectExpr, options: tuple[OptionEntry, ...] = (), docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['contraction_decl'] = 'contraction_decl')

Bases: Statement

contraction NAME(inputs) : DOM -> COD [options].

The option block carries:

  • rule=<NAME> (required): names the composition rule whose join is the fold operation for contracted axes.
  • share=[ax1, ax2, ...]: keep listed axes element-wise even when they appear in multiple inputs.
  • wiring="<einsum>": explicit escape hatch; verbatim einsum string.

ContractionInput didactic-model

ContractionInput(*, name: str, input_domain: ObjectExpr, input_codomain: ObjectExpr, line: int = 0, col: int = 0)

Bases: Model

One input wire of a ContractionDecl declaration.

DecoderDecl didactic-model

DecoderDecl(*, name: str, signature: str, sig_args: tuple[str, ...] = (), options: tuple[OptionEntry, ...] = (), dims: tuple[SortDim, ...] = (), structure: LetExprNode | None = None, structure_arg: str | None = None, primitive: LetExprNode | None = None, primitive_arg: str | None = None, factor: LetExprNode | None = None, factor_arg: str | None = None, binder_select: LetExprNode | None = None, binder_select_arg: str | None = None, recursive_default: bool = True, docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['decoder_decl'] = 'decoder_decl')

Bases: Statement

decoder NAME : SIG[(sig_args)] [options] : body.

DeductionDecl didactic-model

DeductionDecl(*, name: str, domain: ObjectExpr, codomain: ObjectExpr, options: tuple[OptionEntry, ...] = (), atoms: tuple[str, ...] = (), binders: tuple[str, ...] = (), rules: tuple[SequentRule, ...] = (), lexicon: tuple[LexiconEntry, ...] = (), lexicon_from_file: str | None = None, lexicon_from_file_options: tuple[OptionEntry, ...] = (), docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['deduction_decl'] = 'deduction_decl')

Bases: Statement

deduction NAME : DOM -> COD [options] : body.

Body is an indented block of atoms, rule, lexicon entries. The option block carries semiring=..., start=..., depth=..., axioms=..., signature=..., encoder=....

EncoderDecl didactic-model

EncoderDecl(*, name: str, signature: str, sig_args: tuple[str, ...] = (), options: tuple[OptionEntry, ...] = (), dims: tuple[SortDim, ...] = (), iterations: int | None = None, readout: LetExprNode | None = None, op_rules: tuple[EncoderRule, ...] = (), init_rules: tuple[EncoderInitRule, ...] = (), message_rules: tuple[EncoderMessageRule, ...] = (), update_rules: tuple[EncoderUpdateRule, ...] = (), var_inits: tuple[EncoderVarInit, ...] = (), docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['encoder_decl'] = 'encoder_decl')

Bases: Statement

encoder NAME : SIG[(sig_args)] [options] [: body].

The option block carries factory=... (factory-backed form) plus any factory keyword arguments. Body entries are dim, iterations, readout, per-op rules, init/message/update rules, var_init rules.

ExportDecl didactic-model

ExportDecl(*, expr: Expr, docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['export_decl'] = 'export_decl')

Bases: Statement

export EXPR module-level export.

DefineDecl didactic-model

DefineDecl(*, name: str, expr: Expr, where: tuple[Statement, ...] = (), docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['define_decl'] = 'define_decl')

Bases: Statement

define NAME = EXPR [where: nested-defines] value binding.

Unlike a MorphismDecl with role=let, this is a value-level binding: its RHS is an arbitrary morphism Expr, not a morphism signature with an init. The program-step let binds tensor arithmetic instead; the two forms never share a keyword.

The where field is typed as tuple[Statement, ...] (the union root) because didactic does not yet accept self-referential forward refs in field annotations. The parser only ever writes DefineDecl instances into the tuple.

LexiconCategory didactic-model

LexiconCategory()

Bases: TaggedUnion

Category position in a lexicon entry. Three shapes:

  • LexiconCategoryFixed -- a known category, e.g. Det.
  • LexiconCategoryWildcard -- the * wildcard. The compiler treats the entry's category as a latent random variable and learns a Categorical distribution over the deduction's full atom set; one learnable weight is allocated per atom.
  • LexiconCategoryRestricted -- a candidate set {A, B}. Same as wildcard but the Categorical is restricted to the listed atoms; one learnable weight per listed atom.

LexiconCategoryFixed didactic-model

LexiconCategoryFixed(*, category: ObjectExpr, kind: Literal['fixed'] = 'fixed')

Bases: LexiconCategory

"the" : Det = the.

LexiconCategoryRestricted didactic-model

LexiconCategoryRestricted(*, atoms: tuple[str, ...], kind: Literal['restricted'] = 'restricted')

Bases: LexiconCategory

"saw" : {V, N} = saw. Latent over the listed atoms only.

LexiconCategoryWildcard didactic-model

LexiconCategoryWildcard(*, kind: Literal['wildcard'] = 'wildcard')

Bases: LexiconCategory

"bank" : * = bank. Latent over the deduction's atom set.

LexiconEntry didactic-model

LexiconEntry(*, words: tuple[str, ...], category: LexiconCategory, lf: LetExprNode, options: tuple[OptionEntry, ...] = (), line: int = 0, col: int = 0)

Bases: Model

One lexicon-block entry: "word", ... : CAT = LF.

Each word maps to the same category and logical form.

LossDecl didactic-model

LossDecl(*, name: str, options: tuple[OptionEntry, ...] = (), body: LetExprNode, docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['loss_decl'] = 'loss_decl')

Bases: Statement

loss NAME [options] : body.

Option keys: weight=<expr>, on=<attachment>. The on value is an OptionCall of one of program(NAME), deduction(NAME), encoder(NAME), decoder(NAME), rule(NAME, in=DEDUCTION), chart(of=DEDUCTION), or an OptionFlag global.

MorphismDecl didactic-model

MorphismDecl(*, names: tuple[str, ...], domain: ObjectExpr, codomain: ObjectExpr, options: tuple[OptionEntry, ...] = (), init_family: MorphismInitFamily | None = None, init_expr: Expr | None = None, docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['morphism_decl'] = 'morphism_decl')

Bases: Statement

morphism NAME, ... : DOM -> COD [options] [~ init].

Each name declares an independent morphism (fresh parameters) with the same signature, options, and initializer. The morphism's role travels in the option block; the compiler reads options["role"] (kernel when absent) to pick the runtime construction.

Initializer (~ clause, optional):

  • init_family: ~ Family(args) family call (used for kernel priors, latent priors, distribution-driven init).
  • init_expr: ~ <expression> arbitrary morphism-expression (used for explicit values, composition pipelines, ~ auto named recipes).

The two init slots are mutually exclusive; exactly zero or one is populated.

MorphismInitFamily didactic-model

MorphismInitFamily(*, family: str, args: tuple[DrawArg, ...] = (), line: int = 0, col: int = 0)

Bases: Model

~ Family(args) distribution-family initializer.

MorphismParam didactic-model

MorphismParam(*, name: str, domain: ObjectExpr, codomain: ObjectExpr, line: int = 0, col: int = 0, kind: Literal['morphism_param'] = 'morphism_param')

Bases: ProgramParam

Morphism-typed program parameter: f : Mor[A, B].

ObjectParam didactic-model

ObjectParam(*, name: str, universe: Literal['FinSet', 'Space', 'Object'], line: int = 0, col: int = 0, kind: Literal['object_param'] = 'object_param')

Bases: ProgramParam

Object-typed program parameter: G : FinSet / Space / Object.

OptionCall didactic-model

OptionCall(*, func: str, args: tuple[OptionValue, ...] = (), kind: Literal['option_call'] = 'option_call')

Bases: OptionValue

A key bound to a function-call value (e.g. via=product(a, b)).

OptionEntry didactic-model

OptionEntry(*, key: str, value: OptionValue = field(default_factory=OptionFlag), line: int = 0, col: int = 0)

Bases: Model

One key=value (or bare key) entry in an option block.

The list-of-entries layout (rather than a dict) preserves source order; downstream code typically realises a dict on first use.

OptionFlag didactic-model

OptionFlag(*, kind: Literal['option_flag'] = 'option_flag')

Bases: OptionValue

A bare key with no value (e.g. [learnable]).

OptionList didactic-model

OptionList(*, items: tuple[OptionValue, ...] = (), kind: Literal['option_list'] = 'option_list')

Bases: OptionValue

A key bound to a list of identifiers / numbers / strings.

OptionName didactic-model

OptionName(*, value: str, kind: Literal['option_name'] = 'option_name')

Bases: OptionValue

A key bound to a bare identifier (e.g. role=latent).

OptionNumber didactic-model

OptionNumber(*, value: float, kind: Literal['option_number'] = 'option_number')

Bases: OptionValue

A key bound to a numeric literal (e.g. depth=8, scale=0.1).

OptionString didactic-model

OptionString(*, value: str, kind: Literal['option_string'] = 'option_string')

Bases: OptionValue

A key bound to a string literal (e.g. path="lex.tsv").

OptionValue didactic-model

OptionValue()

Bases: TaggedUnion

Value inhabiting one entry of an option block.

Surface shapes:

  • Bare flag [role] -> OptionFlag (no value)
  • role=latent -> OptionName (identifier)
  • depth=8 / scale=0.1 -> OptionNumber
  • path="lex.tsv" -> OptionString
  • over=[a, b] -> OptionList
  • via=product(a, b) -> OptionCall

ProgramDecl didactic-model

ProgramDecl(*, name: str, params: tuple[str, ...] | None = None, type_params: tuple[ProgramParam, ...] | None = None, domain: ObjectExpr, codomain: ObjectExpr, options: tuple[OptionEntry, ...] = (), draws: tuple[ProgramStep, ...] = (), return_vars: tuple[str, ...] = (), return_labels: tuple[str, ...] | None = None, docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['program_decl'] = 'program_decl')

Bases: Statement

program NAME[(params)] : DOM -> COD [options] : body.

Body is a sequence of program steps (sample, observe, marginalize, let) terminated by a return step. Effects, posterior-modifier (over=<model>), and parametric/concrete type-params live in the option block.

ProgramParam didactic-model

ProgramParam()

Bases: TaggedUnion

Sum of typed-program-parameter variants (parametric programs).

RuleDecl didactic-model

RuleDecl(*, name: str, variables: tuple[str, ...], premises: tuple[ObjectExpr, ...], conclusion: ObjectExpr, docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['rule_decl'] = 'rule_decl')

Bases: Statement

rule NAME(variables) : premises |- conclusion declaration.

Premises and conclusion are ObjectExpr patterns drawn from the unified type-expression family.

ScalarParam didactic-model

ScalarParam(*, name: str, scalar_kind: Literal['Real', 'Nat'], line: int = 0, col: int = 0, kind: Literal['scalar_param'] = 'scalar_param')

Bases: ProgramParam

Scalar-typed program parameter: s : Real / Nat.

SchemaDecl didactic-model

SchemaDecl(*, name: str, parameters: tuple[SchemaParameter, ...], domain: ObjectExpr, codomain: ObjectExpr, docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['schema_decl'] = 'schema_decl')

Bases: Statement

schema NAME(parameters) : DOM -> COD declaration.

SchemaParameter didactic-model

SchemaParameter(*, names: tuple[str, ...], type_expr: ObjectExpr, line: int = 0, col: int = 0)

Bases: Model

One names : type group inside a schema's parameter list.

SequentRule didactic-model

SequentRule(*, name: str, premises: tuple[ObjectExpr, ...], conclusion: ObjectExpr, options: tuple[OptionEntry, ...] = (), line: int = 0, col: int = 0)

Bases: Model

A named sequent inside a deduction block.

rule NAME : premises |- conclusion [pragma]. Premise and conclusion type-expressions may contain single-uppercase wildcards (X, Y) that bind to actual category subexpressions when the rule fires.

The trailing pragma carries optional rule-level options:

  • #[learnable] -- allocate one learnable log-weight per distinct binding tuple observed at run time. The bindings tuple is (rule_name, *sorted_binding_values). The conclusion weight becomes semiring_product(premise_weights, param[bindings]).
  • #[weight = expr] -- the conclusion weight is semiring_product(premise_weights, expr) where expr is a let-expression evaluated in the rule's binding scope (wildcards bound by the match are in scope). Most general form; subsumes learnable.
  • #[parent = rule_name] -- compose this rule's weight additively with the named parent rule's weight on the same bindings. Specialisation as a correction term.

SignatureDecl didactic-model

SignatureDecl(*, name: str, params: tuple[str, ...] = (), sorts: tuple[SortDecl, ...] = (), constructors: tuple[ConstructorDecl, ...] = (), binders: tuple[BinderDecl, ...] = (), vertex_kinds: tuple[VertexKindDecl, ...] = (), edge_kinds: tuple[EdgeKindDecl, ...] = (), docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['signature_decl'] = 'signature_decl')

Bases: Statement

signature NAME[(params)] : body.

Statement didactic-model

Statement()

Bases: TaggedUnion

Sum of top-level statement kinds.

ObjectDecl didactic-model

ObjectDecl(*, names: tuple[str, ...], init: TypeInitializer, docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['object_decl'] = 'object_decl')

Bases: Statement

object NAME, ... : VALUE declaration.

Each name registers an independent object with the same VALUE. The VALUE's shape picks the discrete-vs-continuous and reference-vs-initializer distinction; the compiler reads init to decide what kind of object (FinSet, EnumSet, FreeResiduated, FreeMonoid, ContinuousSpace) to register in the env.

TypeEnumSet didactic-model

TypeEnumSet(*, elements: tuple[str, ...], line: int = 0, col: int = 0, kind: Literal['type_enum_set'] = 'type_enum_set')

Bases: TypeInitializer

type Atoms : {NP, S, VP} enum-set initializer.

TypeFreeMonoid didactic-model

TypeFreeMonoid(*, generators: str, max_length: int, line: int = 0, col: int = 0, kind: Literal['type_free_monoid'] = 'type_free_monoid')

Bases: TypeInitializer

type Words : FreeMonoid(Atoms, max_length=N) initializer.

TypeFreeResiduated didactic-model

TypeFreeResiduated(*, generators: str, depth: int = 1, ops: tuple[str, ...] = ('slash',), line: int = 0, col: int = 0, kind: Literal['type_free_residuated'] = 'type_free_residuated')

Bases: TypeInitializer

type Cat : FreeResiduated(Atoms, depth=4, ops=[/, \]) initializer.

TypeFromExpr didactic-model

TypeFromExpr(*, expr: ObjectExpr, kind: Literal['type_from_expr'] = 'type_from_expr')

Bases: TypeInitializer

type X : <type-expression> for every non-special-form value.

Covers integer cardinalities, identifiers, products, coproducts, slashes, effect-applies, and constructor calls (FinSet, Real, Simplex, ...).

TypeInitializer didactic-model

TypeInitializer()

Bases: TaggedUnion

Sum of type NAME : VALUE value shapes.

The grammar's _object_value choice corresponds 1:1 to this union.

Expr didactic-model

Expr()

Bases: TaggedUnion

Sum of value-expression node kinds (morphism computations).

ExprCap didactic-model

ExprCap(*, object_name: str, line: int = 0, col: int = 0, kind: Literal['expr_cap'] = 'expr_cap')

Bases: Expr

Compact-closed counit ε_A : A ⊗ A → I for a named object.

ExprChangeBase didactic-model

ExprChangeBase(*, inner: Expr, phi: Expr, line: int = 0, col: int = 0, kind: Literal['expr_change_base'] = 'expr_change_base')

Bases: Expr

Change-of-base: apply a transformation (an algebra homomorphism or MorphismTransformation) to a morphism.

The transformation is a first-class value: phi is any expression whose compile-time value is a MorphismTransformation or AlgebraHomomorphism. Concretely:

  • A bare identifier resolving a registered singleton (f.change_base(expectation)) or a let-bound trans value (f.change_base(t)).
  • A constructor call (f.change_base(softmax(B))).
  • A composition (f.change_base(t1 >>> t2)).

ExprChartFold didactic-model

ExprChartFold(*, lex: Expr, binary: Expr | None = None, unary: Expr | None = None, start: str | int = 'S', depth: int = 1, effect_depth: int = 0, line: int = 0, col: int = 0, kind: Literal['expr_chart_fold'] = 'expr_chart_fold')

Bases: Expr

Desugared parser-construction primitive.

Surface form: chart_fold(lex=, binary=, unary=, start=, depth=, effect_depth=).

Constructs a chart parser from morphism-valued arguments rather than from a list of named rule schemas. lex is a morphism Token -> Cat; binary is a Cat * Cat -> Cat morphism (the union of all binary rule schemas); unary is an optional Cat -> Cat morphism (the union of all unary rule schemas); start is the goal category name (or integer index); depth is the maximum category nesting depth; effect_depth bounds effect-stack nesting (defaults to 0).

ExprCompose didactic-model

ExprCompose(*, left: Expr, right: Expr, op: str = '>>', line: int = 0, col: int = 0, kind: Literal['expr_compose'] = 'expr_compose')

Bases: Expr

Algebra-typed sequential composition.

The op field selects which enrichment algebra's monoidal structure to use for the V-Cat composition:

  • ">>" for ProductFuzzyAlgebra noisy-OR (the default).
  • "<<" for reverse ProductFuzzyAlgebra.
  • ">=>" for Kleisli composition (operands' shared algebra).
  • "*>" for Markov sum-product.
  • "~>" for LogProb (log-space sum-product).
  • "||>" for Gödel (lattice min/max with Heyting implication).
  • "?>" for Viterbi (max-plus tropical, best path).
  • "&&>" for Boolean (∧/∨).
  • "+>" for Łukasiewicz (probabilistic sum bounded by 1).

Each operator carries its own algebra; cross-operator composition in one chain requires explicit .change_base(φ) between segments.

ExprCup didactic-model

ExprCup(*, object_name: str, line: int = 0, col: int = 0, kind: Literal['expr_cup'] = 'expr_cup')

Bases: Expr

Compact-closed unit η_A : I → A ⊗ A for a named object.

ExprCurry didactic-model

ExprCurry(*, inner: Expr, direction: Literal['right', 'left'], line: int = 0, col: int = 0, kind: Literal['expr_curry'] = 'expr_curry')

Bases: Expr

Residuation-witness curry combinator.

For an inner morphism f : X * Y -> Z whose codomain Z inhabits a residuated universe, f.curry_right denotes the morphism X -> Z/Y and f.curry_left denotes Y -> X\Z.

The categorical interpretation is the right (resp. left) component of the residuation-adjunction unit/counit triangle. Validity of the construction is checked at compile time: domain must factor as a non-commutative product and codomain must inhabit a residuated universe (a FreeResiduated object in scope).

ExprDagger didactic-model

ExprDagger(*, inner: Expr, line: int = 0, col: int = 0, kind: Literal['expr_dagger'] = 'expr_dagger')

Bases: Expr

Compact-closed dagger / transpose of an expression.

ExprFan didactic-model

ExprFan(*, exprs: tuple[Expr, ...], line: int = 0, col: int = 0, kind: Literal['expr_fan'] = 'expr_fan')

Bases: Expr

Fan-out (diagonal) composition: fan(f, g, ...).

ExprFreeze didactic-model

ExprFreeze(*, inner: Expr, line: int = 0, col: int = 0, kind: Literal['expr_freeze'] = 'expr_freeze')

Bases: Expr

Detach gradients: inner.freeze materialises inner's tensor with detach() and wraps the result as a frozen ObservedMorphism. Used to pin a learned composition as a structural input that the downstream model treats as constant.

ExprFromData didactic-model

ExprFromData(*, key: str, line: int = 0, col: int = 0, kind: Literal['expr_from_data'] = 'expr_from_data')

Bases: Expr

Data-derived initializer from_data("KEY").

The string key is resolved against the runtime data dictionary at fit time; the morphism's tensor is the looked-up value. The resulting morphism is ObservedMorphism: its entries are frozen / structural inputs, not learnable parameters.

ExprIdent didactic-model

ExprIdent(*, name: str, line: int = 0, col: int = 0, kind: Literal['expr_ident'] = 'expr_ident')

Bases: Expr

Reference to a named morphism or binding.

ExprIdentity didactic-model

ExprIdentity(*, object_name: str, line: int = 0, col: int = 0, kind: Literal['expr_identity'] = 'expr_identity')

Bases: Expr

Identity morphism: identity(A).

ExprMarginalize didactic-model

ExprMarginalize(*, inner: Expr, names: tuple[str, ...], line: int = 0, col: int = 0, kind: Literal['expr_marginalize'] = 'expr_marginalize')

Bases: Expr

Marginalization: expr.marginalize(A, B, ...).

ExprMorphismCall didactic-model

ExprMorphismCall(*, callee: str, args: tuple[str, ...], line: int = 0, col: int = 0, kind: Literal['expr_morphism_call'] = 'expr_morphism_call')

Bases: Expr

Call expression callee(arg1, arg2, ...) resolving to a morphism-level operation.

Used by ContractionDecl declarations: when the user writes let out = op_apply(arg1, arg2, kernel), the op_apply identifier resolves to a registered contraction and the arguments are looked up in the morphism scope.

ExprParser didactic-model

ExprParser(*, rules: tuple[str, ...] = (), categories: tuple[str, ...] = (), terminal: str | None = None, start: str | int = 'S', depth: int = 1, constructors: tuple[str, ...] | None = None, line: int = 0, col: int = 0, kind: Literal['expr_parser'] = 'expr_parser')

Bases: Expr

Deductive parser assembled from rules.

ExprRepeat didactic-model

ExprRepeat(*, expr: Expr, count: int | None, line: int = 0, col: int = 0, kind: Literal['expr_repeat'] = 'expr_repeat')

Bases: Expr

Iterated composition: repeat(f, n) or repeat(f).

ExprScan didactic-model

ExprScan(*, expr: Expr, init: str = 'zeros', line: int = 0, col: int = 0, kind: Literal['expr_scan'] = 'expr_scan')

Bases: Expr

Temporal scan: scan(cell) or scan(cell, init=learned).

ExprStack didactic-model

ExprStack(*, expr: Expr, count: int, line: int = 0, col: int = 0, kind: Literal['expr_stack'] = 'expr_stack')

Bases: Expr

Independent multi-layer composition: stack(f, n).

ExprTensorProduct didactic-model

ExprTensorProduct(*, left: Expr, right: Expr, line: int = 0, col: int = 0, kind: Literal['expr_tensor_product'] = 'expr_tensor_product')

Bases: Expr

Parallel product: left @ right.

ExprTrace didactic-model

ExprTrace(*, inner: Expr, object_name: str, line: int = 0, col: int = 0, kind: Literal['expr_trace'] = 'expr_trace')

Bases: Expr

Compact-closed trace of an expression along a named object.

ExprTransCompose didactic-model

ExprTransCompose(*, left: Expr, right: Expr, line: int = 0, col: int = 0, kind: Literal['expr_trans_compose'] = 'expr_trans_compose')

Bases: Expr

Composition of two transformations: t1 >>> t2 denotes sequential application, first apply t1, then t2.

Required: t1.target == t2.source (typed at compile time; a mismatch raises CompileError). The result behaves as a transformation with source = t1.source and target = t2.target.

LetExprBinOp didactic-model

LetExprBinOp(*, op: LetBinaryOperator, left: LetExprNode, right: LetExprNode, line: int = 0, col: int = 0, kind: Literal['let_expr_binop'] = 'let_expr_binop')

Bases: LetExprNode

Binary operation in an expression.

PARAMETER DESCRIPTION
op

The operator: arithmetic, comparison, or boolean.

TYPE: LetBinaryOperator

left

The left operand.

TYPE: LetExprNode

right

The right operand.

TYPE: LetExprNode

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "let_expr_binop".

TYPE: Literal['let_expr_binop'] DEFAULT: 'let_expr_binop'

LetExprCall didactic-model

LetExprCall(*, func: str, args: tuple[LetExprNode, ...], line: int = 0, col: int = 0, kind: Literal['let_expr_call'] = 'let_expr_call')

Bases: LetExprNode

Built-in function application in an expression.

PARAMETER DESCRIPTION
func

The builtin's name.

TYPE: str

args

The arguments, in order.

TYPE: tuple[LetExprNode, ...]

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "let_expr_call".

TYPE: Literal['let_expr_call'] DEFAULT: 'let_expr_call'

LetExprFactor didactic-model

LetExprFactor(*, binders: tuple[LetFactorBinder, ...], body: LetExprNode | None = None, cases: tuple[LetFactorCase, ...] = (), line: int = 0, col: int = 0, kind: Literal['let_expr_factor'] = 'let_expr_factor')

Bases: LetExprNode

Multi-axis factor expression: assemble an indexed tensor.

Surface forms:

factor v1 : I1, v2 : I2, ..., vn : In in <body> denotes the tensor of shape (|I1|, ..., |In|, *body_shape) whose value at position (i1, ..., in) is body[v_k := i_k].

factor v : I in { 0 -> e0, 1 -> e1, ... } denotes the single-axis case-structured form: the body at index k is the expression labelled k, and the labels must cover {0, ..., |I|-1} exactly. Multi-axis case form is not accepted; the uniform body form (which can itself contain conditionals on the binders) is the general construction.

Categorically the left adjoint of indexing. Single-axis is a section of the trivial bundle I -> body_type; multi-axis is a section over the product I1 x ... x In. The dual operation is the index pullback arr[i1, ..., in] (LetExprIndex); together they realize the indexed-family colim / lim pair in the slice category over FinSet.

LetExprIndex didactic-model

LetExprIndex(*, array: LetExprNode, indices: tuple[LetExprNode, ...], line: int = 0, col: int = 0, kind: Literal['let_expr_index'] = 'let_expr_index')

Bases: LetExprNode

Indexed access into a finite-domain-indexed family a[i].

Categorically the pullback morphism: given a finite-fibration index : N → A and a per-A morphism arr : A → B, the indexed expression arr[index[n]] denotes arr ∘ index : N → B, the natural Kleisli pullback of arr along index.

ATTRIBUTE DESCRIPTION
array

The indexed-family expression (typically a LetExprVar naming a previously-drawn plate variable).

TYPE: LetExprNode

indices

The index expressions; supports multi-dim indexing for nested plates (coefs[subj[n], k]).

TYPE: tuple of LetExprNode

LetExprLambda didactic-model

LetExprLambda(*, param: str, body: LetExprNode, line: int = 0, col: int = 0, kind: Literal['let_expr_lambda'] = 'let_expr_lambda')

Bases: LetExprNode

Lambda expression param -> body in a let expression.

Closes over the surrounding let-environment at instantiation time. Categorically a curried function in the Kleisli setting; used as the argument to fold / map / filter / reduce combinators.

LetExprList didactic-model

LetExprList(*, items: tuple[LetExprNode, ...], line: int = 0, col: int = 0, kind: Literal['let_expr_list'] = 'let_expr_list')

Bases: LetExprNode

List literal in a let expression: [a, b, c].

Categorically a free-monoid element over the value sublanguage; the runtime represents it as a Python list (with autograd flowing through tensor-valued items).

LetExprLiteral didactic-model

LetExprLiteral(*, value: float, integral: bool = False, line: int = 0, col: int = 0, kind: Literal['let_expr_literal'] = 'let_expr_literal')

Bases: LetExprNode

Numeric literal in an expression.

PARAMETER DESCRIPTION
value

The literal's value.

TYPE: float

integral

Whether the source spelled an integer, with no fraction or exponent. A program step treats every number as real; the QIEC lowerer types an integral literal as Int.

TYPE: bool DEFAULT: False

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "let_expr_literal".

TYPE: Literal['let_expr_literal'] DEFAULT: 'let_expr_literal'

LetExprMethodCall didactic-model

LetExprMethodCall(*, receiver: LetExprNode, method: str, args: tuple[LetExprNode, ...], line: int = 0, col: int = 0, kind: Literal['let_expr_method_call'] = 'let_expr_method_call')

Bases: LetExprNode

Method call receiver.method(args) in a let expression.

The receiver is itself a let-expression (typically a variable reference to a let-bound chart-valued, list-valued, or other object-valued value); the method is dispatched at runtime against the receiver's type. Used primarily for chart-view queries (chart.weight(item), chart.enumerate(pattern), chart.goal_weight()).

LetExprNode didactic-model

LetExprNode()

Bases: TaggedUnion

Sum of pure expression nodes.

One expression tree serves both surfaces: a program let step and a QIEC value position parse to the same nodes. Every node carries the 1-based source line and column of its first token, which the QIEC lowerer needs for diagnostics and stable provenance; a program step ignores them.

LetExprString didactic-model

LetExprString(*, value: str, line: int = 0, col: int = 0, kind: Literal['let_expr_string'] = 'let_expr_string')

Bases: LetExprNode

String literal in a let expression.

Used for tokenisation, lexicon keys, and as ground-atom names in LF constructors like pred("dog") and forall("x", body). The runtime represents these as plain Python strings.

LetExprUnaryOp didactic-model

LetExprUnaryOp(*, operand: LetExprNode, op: Literal['-', 'not'] = '-', line: int = 0, col: int = 0, kind: Literal['let_expr_unary'] = 'let_expr_unary')

Bases: LetExprNode

Unary negation or boolean negation in an expression.

PARAMETER DESCRIPTION
operand

The operand.

TYPE: LetExprNode

op

"-" for arithmetic negation or "not" for boolean negation.

TYPE: Literal['-', 'not'] DEFAULT: '-'

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "let_expr_unary".

TYPE: Literal['let_expr_unary'] DEFAULT: 'let_expr_unary'

LetExprVar didactic-model

LetExprVar(*, name: str, line: int = 0, col: int = 0, kind: Literal['let_expr_var'] = 'let_expr_var')

Bases: LetExprNode

Variable reference in an expression.

PARAMETER DESCRIPTION
name

The variable's name.

TYPE: str

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "let_expr_var".

TYPE: Literal['let_expr_var'] DEFAULT: 'let_expr_var'

LetExprBool didactic-model

LetExprBool(*, value: bool, line: int = 0, col: int = 0, kind: Literal['let_expr_bool'] = 'let_expr_bool')

Bases: LetExprNode

Boolean literal true or false.

PARAMETER DESCRIPTION
value

The literal's value.

TYPE: bool

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "let_expr_bool".

TYPE: Literal['let_expr_bool'] DEFAULT: 'let_expr_bool'

LetExprUnit didactic-model

LetExprUnit(*, line: int = 0, col: int = 0, kind: Literal['let_expr_unit'] = 'let_expr_unit')

Bases: LetExprNode

The unit literal unit.

PARAMETER DESCRIPTION
line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "let_expr_unit".

TYPE: Literal['let_expr_unit'] DEFAULT: 'let_expr_unit'

LetExprTuple didactic-model

LetExprTuple(*, items: tuple[LetExprNode, ...], line: int = 0, col: int = 0, kind: Literal['let_expr_tuple'] = 'let_expr_tuple')

Bases: LetExprNode

Tuple construction (a, b, ...) with at least two components.

PARAMETER DESCRIPTION
items

The components, in order.

TYPE: tuple[LetExprNode, ...]

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "let_expr_tuple".

TYPE: Literal['let_expr_tuple'] DEFAULT: 'let_expr_tuple'

LetFactorBinder didactic-model

LetFactorBinder(*, var: str, index: ObjectExpr, line: int = 0, col: int = 0)

Bases: Model

One <var> : <Index> binder in a multi-axis factor expression.

The variable name binds to integer index values 0, 1, ..., |Index|-1 in the surrounding factor body. The index type expression resolves to a finite-set object whose cardinality is the corresponding axis size of the constructed tensor.

LetFactorCase didactic-model

LetFactorCase(*, label: int, value: LetExprNode, line: int = 0, col: int = 0)

Bases: Model

One <integer> -> <body> case in a factor pattern-match.

The label is the integer index this case populates; the body is the value at that index. The compiler verifies that the union of labels across all cases covers {0, ..., |Index|-1} exactly.

Module didactic-model

Module(*, statements: tuple[Statement, ...] = field(default_factory=tuple))

Bases: Model

A complete .qvr program (sequence of statements).

BindStep didactic-model

BindStep(*, vars: tuple[str, ...], morphism: str, args: tuple[DrawArg, ...] | None = None, index: ObjectExpr | None = None, mode: Literal['sample', 'score', 'marginal'] = 'sample', scope: tuple[ProgramStep, ...] | None = None, axes: AxisSpec | None = None, over: str | None = None, over_objs: tuple[str, ...] | None = None, via: str | None = None, via_axes: tuple[str, ...] | None = None, reduction: str | None = None, line: int = 0, col: int = 0, kind: Literal['bind_step'] = 'bind_step')

Bases: ProgramStep

Internal compiler IR: a unified Kleisli bind.

Synthesized from surface SampleStep / ObserveStep / MarginalizeStep during template instantiation. The surface AST never carries this shape directly.

CallStep didactic-model

CallStep(*, name: str, call: QiecCallComputation, line: int = 0, col: int = 0, kind: Literal['call_step'] = 'call_step')

Bases: ProgramStep

let name <- computation(args) binding step.

The bound name takes the result of a named computation declared in the module; the computation's effects join the program's row.

DrawArg didactic-model

DrawArg()

Bases: TaggedUnion

A single argument in a draw step. Variants cover all four surface shapes the parser can produce: bare identifier (variable reference), numeric literal, distribution-call expression (compositional measure algebra), and list of args.

Sum-type representation rather than a Python union so the panproto translation can carry the AST through the grammar walker, the migration lens, and the pretty-printer uniformly.

DrawArgDist didactic-model

DrawArgDist(*, family: str, args: tuple[DrawArg, ...], line: int = 0, col: int = 0, kind: Literal['dist'] = 'dist')

Bases: DrawArg

Nested Family(...) call inside the args of a draw step.

Surfaces the compositional measure algebra (Mixture, Restrict, Pushforward, PointMass, ...) so distributions can be expressed as ordinary draw-arg expressions:

observe y <- Mixture([0.3, 0.7], [PointMass(0), Poisson(rate)])

The compiler recurses into args to build the inner measure before passing it to the outer family's builder.

DrawArgIndex didactic-model

DrawArgIndex(*, name: str, indices: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['index'] = 'index')

Bases: DrawArg

Bracket-indexed reference in a draw step. name is the base tensor identifier; indices is the tuple of index-tensor identifiers referenced inside the brackets (typically length one, e.g. theta[N]). Both the base name and every index identifier count as dependencies for plate-graph edge emission.

DrawArgList didactic-model

DrawArgList(*, items: tuple[DrawArg, ...], line: int = 0, col: int = 0, kind: Literal['list'] = 'list')

Bases: DrawArg

List-of-draw-args, e.g. [0.3, 0.7] for mixture weights or [PointMass(0), Poisson(rate)] for mixture components. The compiler unpacks the list into a vector or list of inner distributions depending on the consuming family's argument schema.

DrawArgName didactic-model

DrawArgName(*, text: str, line: int = 0, col: int = 0, kind: Literal['name'] = 'name')

Bases: DrawArg

Bare identifier reference in a draw step. Carries only the identifier text; bracket-indexed forms (theta[N]) parse to the dedicated DrawArgIndex variant.

DrawArgNamed didactic-model

DrawArgNamed(*, parameter: str, value: DrawArg, line: int = 0, col: int = 0, kind: Literal['named'] = 'named')

Bases: DrawArg

One keyword argument in a distribution-family construction.

The parameter name is structural: it wraps the argument value instead of being optional metadata on that value. Rewriters must therefore preserve or deliberately transform the complete named entry, and cannot accidentally erase a parameterization while rebuilding its value.

DrawArgScalar didactic-model

DrawArgScalar(*, value: float, line: int = 0, col: int = 0, kind: Literal['scalar'] = 'scalar')

Bases: DrawArg

Numeric literal in a draw step.

DrawStep didactic-model

DrawStep(*, vars: tuple[str, ...], morphism: str, args: tuple[DrawArg, ...] | None = None, is_observed: bool = False, axes: AxisSpec | None = None, line: int = 0, col: int = 0, kind: Literal['draw_step'] = 'draw_step')

Bases: ProgramStep

Internal compiler IR: a scalar sample or score step.

Synthesised from a SampleStep/ObserveStep with no index annotation; is_observed distinguishes sample (False) from score (True).

GroupedBodyObserveStep didactic-model

GroupedBodyObserveStep(*, response_var: str, morphism: str, args: tuple[DrawArg, ...] | None = None, index_set: ObjectExpr | None = None, index_var: str = '', latent_name: str = '', class_size: int = 0, fibration_var: str | None = None, fibration_axes: tuple[str, ...] | None = None, ll_slot: str = '', line: int = 0, col: int = 0, kind: Literal['grouped_body_observe_step'] = 'grouped_body_observe_step')

Bases: ProgramStep

Internal compiler IR: a captured observe inside a grouped marginalize block.

GroupedLatentInitStep didactic-model

GroupedLatentInitStep(*, latent_name: str, class_size: int, line: int = 0, col: int = 0, kind: Literal['grouped_latent_init_step'] = 'grouped_latent_init_step')

Bases: ProgramStep

Internal compiler IR: initialise the latent's env slot to torch.arange(class_size) at the start of a grouped marginalize block's body.

GroupedMarginalizeStep didactic-model

GroupedMarginalizeStep(*, var_name: str, class_size: int, probs_var: str | None = None, probs_indices: tuple[str, ...] = (), parameterization: Literal['probs', 'logits'] = 'probs', over_obj: str | None = None, over_objs: tuple[str, ...] | None = None, body_ll_var: str = '', body_observes: tuple[GroupedObserveEntry, ...] | None = None, reduction: str | None = None, line: int = 0, col: int = 0, kind: Literal['grouped_marginalize_step'] = 'grouped_marginalize_step')

Bases: ProgramStep

Internal compiler IR: a marginalisation pushforward.

The compiler lowers a surface MarginalizeStep into this shape after expanding the scope. class_size is the resolved cardinality of the latent index; probs_var names the env slot holding the family's probability or logits tensor, which probs_indices gather rows of, left to right, when the prior is written probs[latent] against an enclosing latent; parameterization records whether that tensor is probabilities or logits; over_obj / over_objs carry the grouping object (single or product); body_ll_var names the env slot that the grouped observe pushed its (N_m, K) log-likelihood into; body_observes lists the (ll_slot, fibration) entries that the runtime callable consumes for grouped pushforward.

GroupedObserveEntry didactic-model

GroupedObserveEntry(*, ll_slot: str, fibration_var: str | None = None, fibration_axes: tuple[str, ...] | None = None, inner_groups: tuple[str, ...] | None = None, line: int = 0, col: int = 0)

Bases: Model

One entry in a GroupedMarginalizeStep's body_observes list.

Pairs an env slot (where the captured observe writes its (N_m, K) log-likelihood) with the fibration that carries those rows into the shared grouping plate. An entry with no fibration is a nested grouped block: the slot holds the inner block's per-position aggregates over inner_groups, which the enclosing block projects onto its own grouping plate.

LetStep didactic-model

LetStep(*, name: str, value: LetExprNode, line: int = 0, col: int = 0, kind: Literal['let_step'] = 'let_step')

Bases: ProgramStep

let name = value deterministic step.

The value is a let-arithmetic expression evaluated against the surrounding program env.

MarginalizeStep didactic-model

MarginalizeStep(*, var: str, morphism: str, args: tuple[DrawArg, ...] | None = None, index: ObjectExpr | None = None, over: str | None = None, over_objs: tuple[str, ...] | None = None, reduction: str | None = None, options: tuple[OptionEntry, ...] = (), scope: tuple[ProgramStep, ...] = (), line: int = 0, col: int = 0, kind: Literal['marginalize_step'] = 'marginalize_step')

Bases: ProgramStep

marginalize var[: index] <- morphism(args) [options] : scope.

Introduces a coordinate, executes the scope's steps with that coordinate in trace context, and at the end of the scope pushes forward through the projection (logsumexp for discrete, fibrewise integration for continuous). When the option block carries over=..., the reduction is fibred (grouped marginalize); the via clause on each inner observe names the per-observe fibration.

ObserveStep didactic-model

ObserveStep(*, vars: tuple[str, ...], morphism: str, args: tuple[DrawArg, ...] | None = None, index: ObjectExpr | None = None, axes: AxisSpec | None = None, via: str | None = None, via_axes: tuple[str, ...] | None = None, options: tuple[OptionEntry, ...] = (), line: int = 0, col: int = 0, kind: Literal['observe_step'] = 'observe_step')

Bases: ProgramStep

observe vars[: index] <- morphism(args) [options].

Scored Kleisli bind; the bound coordinate is clamped at runtime by the observations dict, making the resulting kernel sub-probabilistic. vars shares the pattern shape with SampleStep (a bare name or a parenthesized tuple); the compiler validates arity against the morphism's codomain.

PlateDrawStep didactic-model

PlateDrawStep(*, name: str, index: ObjectExpr, codomain: ObjectExpr, morphism: str, args: tuple[DrawArg, ...] | None = None, axes: AxisSpec | None = None, line: int = 0, col: int = 0, kind: Literal['plate_draw_step'] = 'plate_draw_step')

Bases: ProgramStep

Internal compiler IR: an A-indexed sample step.

Synthesised from a SampleStep with an index annotation; realises a Kern-morphism A -> Kern(K) as a tensor of shape (|A|, *K.shape).

ProgramStep didactic-model

ProgramStep()

Bases: TaggedUnion

Sum of program-block step node kinds.

ReturnStep didactic-model

ReturnStep(*, vars: tuple[str, ...], labels: tuple[str, ...] | None = None, line: int = 0, col: int = 0, kind: Literal['return_step'] = 'return_step')

Bases: ProgramStep

return v or return (a, b) or return (a: x, b: y) step.

Always the terminal step of a program body. labels is non-None for the labelled-tuple form return (a: x, b: y).

SampleStep didactic-model

SampleStep(*, vars: tuple[str, ...], morphism: str, args: tuple[DrawArg, ...] | None = None, index: ObjectExpr | None = None, axes: AxisSpec | None = None, options: tuple[OptionEntry, ...] = (), line: int = 0, col: int = 0, kind: Literal['sample_step'] = 'sample_step')

Bases: ProgramStep

sample vars[: index] <- morphism(args) [options].

Surface forms::

sample v <- F(args)                         # scalar draw
sample v : A <- F(args)                     # A-indexed plate
sample (a, b) <- F(args)                    # destructuring tuple

Optional [options] block carries axis-role and other family-level config ([over=[...], iid=[...]]).

ScoreStep didactic-model

ScoreStep(*, name: str, value: LetExprNode, line: int = 0, col: int = 0, kind: Literal['score_step'] = 'score_step')

Bases: ProgramStep

score name = value log-density factor step.

Like LetStep in that name is bound to the evaluated expression's value for downstream reference, but distinct in that the value is additionally added to the program's log_joint. This is the deduction-style analog of ObserveStep: the chart's goal_weight is a log-density factor on the corpus, and score log_Z = chart.goal_weight() expresses that contribution as a first-class step.

VectorisedObserveStep didactic-model

VectorisedObserveStep(*, index_var: str, index_set: ObjectExpr, morphism: str, args: tuple[DrawArg, ...] | None = None, response_var: str = '', fibration_var: str | None = None, fibration_axes: tuple[str, ...] | None = None, line: int = 0, col: int = 0, kind: Literal['vectorized_observe_step'] = 'vectorized_observe_step')

Bases: ProgramStep

Internal compiler IR: an A-indexed score step.

Synthesised from an ObserveStep with an index annotation; denotes the sub-probabilistic kernel Phi -> Kern_{<=1}(Phi) with score prod_n p_F(r_obs(n); theta(n, phi)).

QiecBindComputation didactic-model

QiecBindComputation(*, binder: QiecLocalBinding, first: QiecComputation, then: QiecComputation, line: int = 0, col: int = 0, kind: Literal['qiec_bind_computation'] = 'qiec_bind_computation')

Bases: QiecComputation

let x <- FIRST followed by a computation reading x.

PARAMETER DESCRIPTION
binder

The local the first computation's result is bound to.

TYPE: QiecLocalBinding

first

The computation run first.

TYPE: QiecComputation

then

The computation the binding scopes over.

TYPE: QiecComputation

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_bind_computation".

TYPE: Literal['qiec_bind_computation'] DEFAULT: 'qiec_bind_computation'

QiecBinder didactic-model

QiecBinder()

Bases: TaggedUnion

One entry in a heterogeneous static telescope.

QiecCaseBranch didactic-model

QiecCaseBranch(*, constructor: str, static_arguments: tuple[QiecStaticArgument, ...] = (), fields: tuple[QiecLocalBinding, ...] = (), body: QiecComputation, line: int = 0, col: int = 0)

Bases: Model

One branch of a case analysis over an indexed family value.

PARAMETER DESCRIPTION
constructor

The constructor the branch matches.

TYPE: str

static_arguments

The constructor-local static arguments the branch binds.

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

fields

The field binders, in declaration order.

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

body

The branch body.

TYPE: QiecComputation

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

QiecCaseComputation didactic-model

QiecCaseComputation(*, scrutinee: QiecValue, motive: QiecCaseMotive, branches: tuple[QiecCaseBranch, ...], line: int = 0, col: int = 0, kind: Literal['qiec_case_computation'] = 'qiec_case_computation')

Bases: QiecComputation

Case analysis over an indexed family value.

PARAMETER DESCRIPTION
scrutinee

The value analysed.

TYPE: QiecValue

motive

The motive the branches are checked against.

TYPE: QiecCaseMotive

branches

The branches, one per constructor covered.

TYPE: tuple[QiecCaseBranch, ...]

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_case_computation".

TYPE: Literal['qiec_case_computation'] DEFAULT: 'qiec_case_computation'

QiecIfComputation didactic-model

QiecIfComputation(*, condition: QiecValue, then: QiecComputation, otherwise: QiecComputation, line: int = 0, col: int = 0, kind: Literal['qiec_if_computation'] = 'qiec_if_computation')

Bases: QiecComputation

if COND then ... else ..., branching on a Boolean value.

PARAMETER DESCRIPTION
condition

The Boolean value branched on.

TYPE: QiecValue

then

The computation run when the condition holds.

TYPE: QiecComputation

otherwise

The computation run when it does not.

TYPE: QiecComputation

line

The 1-based source line.

TYPE: int DEFAULT: 0

col

The 0-based source column.

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_if_computation".

TYPE: Literal['qiec_if_computation'] DEFAULT: 'qiec_if_computation'

QiecCaseMotive didactic-model

QiecCaseMotive(*, indices: tuple[QiecIndexBinder, ...], result_type: QiecTypeExpr, line: int = 0, col: int = 0)

Bases: Model

The motive of a case analysis: the indices it abstracts and the result type they determine.

PARAMETER DESCRIPTION
indices

The index binders the motive abstracts over.

TYPE: tuple[QiecIndexBinder, ...]

result_type

The result type under those binders.

TYPE: QiecTypeExpr

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

QiecComputation didactic-model

QiecComputation()

Bases: TaggedUnion

A computation in the QIEC fine-grain call-by-value surface.

QiecComputationDecl didactic-model

QiecComputationDecl(*, name: str, binders: tuple[QiecBinder, ...] = (), parameters: tuple[QiecValueParameter, ...] = (), result_type: QiecTypeExpr, effects: QiecEffectRow, body: QiecComputation, docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['computation_decl'] = 'computation_decl')

Bases: Statement

define NAME[binders](params) : TYPE !ROW = BODY, a named computation.

PARAMETER DESCRIPTION
name

The computation's name.

TYPE: str

binders

The static telescope.

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

parameters

The value parameters.

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

result_type

The declared result type.

TYPE: QiecTypeExpr

effects

The declared effect row.

TYPE: QiecEffectRow

body

The body.

TYPE: QiecComputation

docs

The doc comment lines attached to the declaration.

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

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "computation_decl".

TYPE: Literal['computation_decl'] DEFAULT: 'computation_decl'

QiecConstructorValue didactic-model

QiecConstructorValue(*, constructor: str, static_arguments: tuple[QiecStaticArgument, ...] = (), fields: tuple[QiecValue, ...] = (), result_type: QiecTypeExpr, line: int = 0, col: int = 0, kind: Literal['qiec_constructor_value'] = 'qiec_constructor_value')

Bases: LetExprNode

Application of a family constructor, construct C[..](..) as T.

PARAMETER DESCRIPTION
constructor

The constructor's name.

TYPE: str

static_arguments

The family parameters and constructor-local static arguments.

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

fields

The field values, in declaration order.

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

result_type

The family type the value inhabits.

TYPE: QiecTypeExpr

line

The 1-based source line.

TYPE: int DEFAULT: 0

col

The 0-based source column.

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_constructor_value".

TYPE: Literal['qiec_constructor_value'] DEFAULT: 'qiec_constructor_value'

QiecEffectBinder didactic-model

QiecEffectBinder(*, name: str, line: int = 0, col: int = 0, kind: Literal['qiec_effect_binder'] = 'qiec_effect_binder')

Bases: QiecBinder

A telescope binder over effect interfaces.

PARAMETER DESCRIPTION
name

The binder's name.

TYPE: str

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_effect_binder".

TYPE: Literal['qiec_effect_binder'] DEFAULT: 'qiec_effect_binder'

QiecEffectDecl didactic-model

QiecEffectDecl(*, name: str, binders: tuple[QiecBinder, ...] = (), operations: tuple[QiecOperationDecl, ...] = (), docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['effect_decl'] = 'effect_decl')

Bases: Statement

effect NAME[binders] declaring an operation interface.

PARAMETER DESCRIPTION
name

The interface's name.

TYPE: str

binders

The interface's static telescope.

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

operations

The operations declared.

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

docs

The doc comment lines attached to the declaration.

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

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "effect_decl".

TYPE: Literal['effect_decl'] DEFAULT: 'effect_decl'

QiecEffectInstanceDecl didactic-model

QiecEffectInstanceDecl(*, name: str, effect: QiecEffectRef, docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['effect_instance_decl'] = 'effect_instance_decl')

Bases: Statement

instance NAME : EFFECT, a module-level lexical effect instance.

PARAMETER DESCRIPTION
name

The instance's name.

TYPE: str

effect

The applied interface the instance carries.

TYPE: QiecEffectRef

docs

The doc comment lines attached to the declaration.

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

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "effect_instance_decl".

TYPE: Literal['effect_instance_decl'] DEFAULT: 'effect_instance_decl'

QiecEffectKind didactic-model

QiecEffectKind(*, line: int = 0, col: int = 0, kind: Literal['qiec_effect_kind'] = 'qiec_effect_kind')

Bases: QiecKindExpr

The kind Effect of effect interfaces.

PARAMETER DESCRIPTION
line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_effect_kind".

TYPE: Literal['qiec_effect_kind'] DEFAULT: 'qiec_effect_kind'

QiecEffectRef didactic-model

QiecEffectRef(*, name: str, arguments: tuple[QiecStaticArgument, ...] = (), line: int = 0, col: int = 0)

Bases: Model

An applied effect interface such as State[Int].

QiecEffectRequest didactic-model

QiecEffectRequest(*, instance: str, operation: str, static_arguments: tuple[QiecStaticArgument, ...] = (), arguments: tuple[QiecValue, ...] = (), line: int = 0, col: int = 0)

Bases: Model

A request of one operation on a lexical effect instance.

PARAMETER DESCRIPTION
instance

The instance's name.

TYPE: str

operation

The operation's name.

TYPE: str

static_arguments

The static arguments the operation's telescope takes.

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

arguments

The value arguments, in order.

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

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

QiecEffectRow didactic-model

QiecEffectRow(*, entries: tuple[QiecRowEntry, ...] = (), tail: str | None = None, lacks: tuple[str, ...] = (), line: int = 0, col: int = 0)

Bases: Model

Explicit row entries plus an optional constrained open tail.

QiecFamilyConstructor didactic-model

QiecFamilyConstructor(*, name: str, binders: tuple[QiecBinder, ...] = (), arguments: tuple[QiecTypeExpr, ...] = (), result: QiecTypeExpr, line: int = 0, col: int = 0)

Bases: Model

A GADT constructor with a local telescope and refined result.

QiecFamilyDecl didactic-model

QiecFamilyDecl(*, name: str, parameters: tuple[QiecBinder, ...] = (), indices: tuple[QiecIndexBinder, ...] = (), result_kind: QiecKindExpr, constructors: tuple[QiecFamilyConstructor, ...] = (), docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['indexed_family_decl'] = 'indexed_family_decl')

Bases: Statement

family NAME[params](indices) : KIND with its GADT constructors.

PARAMETER DESCRIPTION
name

The family's name.

TYPE: str

parameters

The uniform static parameters.

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

indices

The refinable index binders.

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

result_kind

The kind of the family's applications.

TYPE: QiecKindExpr

constructors

The family's constructors.

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

docs

The doc comment lines attached to the declaration.

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

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "indexed_family_decl".

TYPE: Literal['indexed_family_decl'] DEFAULT: 'indexed_family_decl'

QiecFunctionType didactic-model

QiecFunctionType(*, parameter: QiecTypeExpr, result: QiecTypeExpr, line: int = 0, col: int = 0, kind: Literal['qiec_function_type'] = 'qiec_function_type')

Bases: QiecTypeExpr

A function type between value types.

PARAMETER DESCRIPTION
parameter

The parameter type.

TYPE: QiecTypeExpr

result

The result type.

TYPE: QiecTypeExpr

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_function_type".

TYPE: Literal['qiec_function_type'] DEFAULT: 'qiec_function_type'

QiecHandleComputation didactic-model

QiecHandleComputation(*, instance: str, handler: QiecHandlerApplication, body: QiecComputation, line: int = 0, col: int = 0, kind: Literal['qiec_handle_computation'] = 'qiec_handle_computation')

Bases: QiecComputation

A computation run under a handler installed for one instance.

PARAMETER DESCRIPTION
instance

The instance the handler is installed for.

TYPE: str

handler

The handler applied.

TYPE: QiecHandlerApplication

body

The computation run under it.

TYPE: QiecComputation

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_handle_computation".

TYPE: Literal['qiec_handle_computation'] DEFAULT: 'qiec_handle_computation'

QiecHandlerApplication didactic-model

QiecHandlerApplication(*, name: str, static_arguments: tuple[QiecStaticArgument, ...] = (), line: int = 0, col: int = 0)

Bases: Model

A handler applied to the static arguments its telescope takes.

PARAMETER DESCRIPTION
name

The handler's name.

TYPE: str

static_arguments

The static arguments, in order.

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

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

QiecCallComputation didactic-model

QiecCallComputation(*, callee: str, static_arguments: tuple[QiecStaticArgument, ...] = (), arguments: tuple[QiecValue, ...] = (), line: int = 0, col: int = 0, kind: Literal['qiec_call_computation'] = 'qiec_call_computation')

Bases: QiecComputation

Application of a named computation.

The callee is resolved against the module's signature table rather than against a local binding, so a call may precede the declaration it names and mutual recursion needs no forward declaration.

QiecHandlerClause didactic-model

QiecHandlerClause()

Bases: TaggedUnion

One clause of a handler declaration.

A handler answers a returning computation and each operation it covers, and those are different shapes: the return clause binds a value, an operation clause binds the operation's arguments and may resume.

QiecHandlerReturnClause didactic-model

QiecHandlerReturnClause(*, binder: QiecLocalBinding, body: QiecComputation, line: int = 0, col: int = 0, kind: Literal['qiec_handler_return_clause'] = 'qiec_handler_return_clause')

Bases: QiecHandlerClause

What a handler does with the value its computation returns.

QiecHandlerOperationClause didactic-model

QiecHandlerOperationClause(*, operation: str, grade: QiecResumptionGrade, binders: tuple[QiecBinder, ...] = (), parameters: tuple[QiecLocalBinding, ...] = (), body: QiecComputation | None = None, line: int = 0, col: int = 0, kind: Literal['qiec_handler_operation_clause'] = 'qiec_handler_operation_clause')

Bases: QiecHandlerClause

One operation a handler covers.

A body of None is a signature rather than an implementation, and is legal only where the declaration says implementation=foreign.

QiecHandlerDecl didactic-model

QiecHandlerDecl(*, name: str, binders: tuple[QiecBinder, ...] = (), effect: QiecEffectRef, input_type: QiecTypeExpr, output_type: QiecTypeExpr, introduced: QiecEffectRow = QiecEffectRow(), coverage: Literal['total', 'partial'] = 'total', forwards_unknown: bool = False, implementation: QiecHandlerImplementation = 'authored', clauses: tuple[QiecHandlerClause, ...] = (), duplicate_options: tuple[str, ...] = (), docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['handler_decl'] = 'handler_decl')

Bases: Statement

handler NAME[binders] for EFFECT : IN => OUT with its clauses.

PARAMETER DESCRIPTION
name

The handler's name.

TYPE: str

binders

The handler's static telescope.

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

effect

The applied interface the handler handles.

TYPE: QiecEffectRef

input_type

The type of the computation handled.

TYPE: QiecTypeExpr

output_type

The type the handled computation yields.

TYPE: QiecTypeExpr

introduced

The effect row the handler's clauses may perform.

TYPE: QiecEffectRow DEFAULT: QiecEffectRow()

coverage

Whether the clauses cover every operation (total) or forward the rest (partial).

TYPE: Literal['total', 'partial'] DEFAULT: 'total'

forwards_unknown

Whether requests of operations without a clause are forwarded outward.

TYPE: bool DEFAULT: False

implementation

Whether the clause bodies are authored here or supplied by a runtime provider.

TYPE: QiecHandlerImplementation DEFAULT: 'authored'

clauses

The return and operation clauses.

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

duplicate_options

The option names the source repeated, kept so the checker can report them.

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

docs

The doc comment lines attached to the declaration.

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

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "handler_decl".

TYPE: Literal['handler_decl'] DEFAULT: 'handler_decl'

QiecContextSort didactic-model

QiecContextSort(*, signature: str, line: int = 0, col: int = 0, kind: Literal['qiec_context_sort'] = 'qiec_context_sort')

Bases: QiecIndexSort

The sort of contexts over a structural signature.

PARAMETER DESCRIPTION
signature

The signature's name.

TYPE: str

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_context_sort".

TYPE: Literal['qiec_context_sort'] DEFAULT: 'qiec_context_sort'

QiecInstanceComputation didactic-model

QiecInstanceComputation(*, name: str, effect: QiecEffectRef, body: QiecComputation, line: int = 0, col: int = 0, kind: Literal['qiec_instance_computation'] = 'qiec_instance_computation')

Bases: QiecComputation

with instance x : E in, allocating a lexically scoped instance.

The binder is live only in body. Its identity is derived rather than generated, so the same allocation site yields the same instance on every run.

QiecIndexApplication didactic-model

QiecIndexApplication(*, constructor: str, arguments: tuple[QiecIndexExpr, ...] = (), line: int = 0, col: int = 0, kind: Literal['qiec_index_application'] = 'qiec_index_application')

Bases: QiecIndexExpr

A user index-sort constructor applied to index arguments.

PARAMETER DESCRIPTION
constructor

The constructor's name.

TYPE: str

arguments

The index arguments, in order.

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

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_index_application".

TYPE: Literal['qiec_index_application'] DEFAULT: 'qiec_index_application'

QiecIndexBinder didactic-model

QiecIndexBinder(*, name: str, sort: QiecIndexSort, line: int = 0, col: int = 0, kind: Literal['qiec_index_binder'] = 'qiec_index_binder')

Bases: QiecBinder

A telescope binder over a closed index sort.

PARAMETER DESCRIPTION
name

The binder's name.

TYPE: str

sort

The sort the binder ranges over.

TYPE: QiecIndexSort

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_index_binder".

TYPE: Literal['qiec_index_binder'] DEFAULT: 'qiec_index_binder'

QiecIndexConstructor didactic-model

QiecIndexConstructor(*, name: str, arguments: tuple[QiecIndexSort, ...] = (), line: int = 0, col: int = 0)

Bases: Model

One constructor of a closed user-defined index sort.

QiecIndexDecl didactic-model

QiecIndexDecl(*, name: str, constructors: tuple[QiecIndexConstructor, ...], docs: tuple[str, ...] = (), line: int = 0, col: int = 0, kind: Literal['index_decl'] = 'index_decl')

Bases: Statement

index NAME = C1 | C2(...) | ..., a closed user index sort.

PARAMETER DESCRIPTION
name

The sort's name.

TYPE: str

constructors

The sort's constructors.

TYPE: tuple[QiecIndexConstructor, ...]

docs

The doc comment lines attached to the declaration.

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

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "index_decl".

TYPE: Literal['index_decl'] DEFAULT: 'index_decl'

QiecIndexExpr didactic-model

QiecIndexExpr()

Bases: TaggedUnion

A source-level term in a closed index sort.

QiecIndexLiteral didactic-model

QiecIndexLiteral(*, value: int, line: int = 0, col: int = 0, kind: Literal['qiec_index_literal'] = 'qiec_index_literal')

Bases: QiecIndexExpr

A natural-number index literal.

PARAMETER DESCRIPTION
value

The literal's value.

TYPE: int

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_index_literal".

TYPE: Literal['qiec_index_literal'] DEFAULT: 'qiec_index_literal'

QiecIndexName didactic-model

QiecIndexName(*, name: str, line: int = 0, col: int = 0, kind: Literal['qiec_index_name'] = 'qiec_index_name')

Bases: QiecIndexExpr

A reference to an index binder in scope.

PARAMETER DESCRIPTION
name

The binder's name.

TYPE: str

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_index_name".

TYPE: Literal['qiec_index_name'] DEFAULT: 'qiec_index_name'

QiecIndexSort didactic-model

QiecIndexSort()

Bases: TaggedUnion

A closed index sort annotation.

QiecKindExpr didactic-model

QiecKindExpr()

Bases: TaggedUnion

A QIEC kind appearing in source.

QiecLocalBinding didactic-model

QiecLocalBinding(*, name: str, type_expr: QiecTypeExpr | None = None, line: int = 0, col: int = 0)

Bases: Model

A local name bound by a computation, with an optional type annotation.

PARAMETER DESCRIPTION
name

The local's name.

TYPE: str

type_expr

The annotated type, or None when inferred.

TYPE: QiecTypeExpr | None DEFAULT: None

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

QiecOperationDecl didactic-model

QiecOperationDecl(*, name: str, binders: tuple[QiecBinder, ...] = (), arguments: tuple[QiecTypeExpr, ...] = (), result: QiecTypeExpr, line: int = 0, col: int = 0)

Bases: Model

One operation of an effect interface declaration.

PARAMETER DESCRIPTION
name

The operation's name.

TYPE: str

binders

The operation's own static telescope.

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

arguments

The argument types, in order.

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

result

The result type.

TYPE: QiecTypeExpr

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

QiecPerformComputation didactic-model

QiecPerformComputation(*, request: QiecEffectRequest, line: int = 0, col: int = 0, kind: Literal['qiec_perform_computation'] = 'qiec_perform_computation')

Bases: QiecComputation

perform of one effect request.

PARAMETER DESCRIPTION
request

The request performed.

TYPE: QiecEffectRequest

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_perform_computation".

TYPE: Literal['qiec_perform_computation'] DEFAULT: 'qiec_perform_computation'

QiecProductType didactic-model

QiecProductType(*, components: tuple[QiecTypeExpr, ...], line: int = 0, col: int = 0, kind: Literal['qiec_product_type'] = 'qiec_product_type')

Bases: QiecTypeExpr

A finite product of value types.

PARAMETER DESCRIPTION
components

The component types, in order.

TYPE: tuple[QiecTypeExpr, ...]

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_product_type".

TYPE: Literal['qiec_product_type'] DEFAULT: 'qiec_product_type'

QiecPureBinding didactic-model

QiecPureBinding(*, binder: QiecLocalBinding, value: QiecValue, then: QiecComputation, line: int = 0, col: int = 0, kind: Literal['qiec_pure_binding'] = 'qiec_pure_binding')

Bases: QiecComputation

let x = VALUE, binding a pure expression.

Separate from QiecBindComputation, which binds a computation's result. The two have different typing rules and neither is sugar for the other.

PARAMETER DESCRIPTION
binder

The local the value is bound to.

TYPE: QiecLocalBinding

value

The pure expression.

TYPE: QiecValue

then

The computation the binding scopes over.

TYPE: QiecComputation

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_pure_binding".

TYPE: Literal['qiec_pure_binding'] DEFAULT: 'qiec_pure_binding'

QiecResumeComputation didactic-model

QiecResumeComputation(*, value: QiecValue | None = None, line: int = 0, col: int = 0, kind: Literal['qiec_resume_computation'] = 'qiec_resume_computation')

Bases: QiecComputation

Invocation of the enclosing handler clause's continuation.

The resumption is not a named local, so there is exactly one way to invoke it. A value of None resumes with unit.

QiecReturnComputation didactic-model

QiecReturnComputation(*, value: QiecValue, line: int = 0, col: int = 0, kind: Literal['qiec_return_computation'] = 'qiec_return_computation')

Bases: QiecComputation

return VALUE, the computation that performs nothing.

PARAMETER DESCRIPTION
value

The value returned.

TYPE: QiecValue

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_return_computation".

TYPE: Literal['qiec_return_computation'] DEFAULT: 'qiec_return_computation'

QiecRowEntry didactic-model

QiecRowEntry(*, instance: str, line: int = 0, col: int = 0)

Bases: Model

A named lexical effect instance in an effect row.

QiecSequenceComputation didactic-model

QiecSequenceComputation(*, first: QiecComputation, then: QiecComputation, line: int = 0, col: int = 0, kind: Literal['qiec_sequence_computation'] = 'qiec_sequence_computation')

Bases: QiecComputation

Two computations run in order, the first result discarded.

PARAMETER DESCRIPTION
first

The computation run first.

TYPE: QiecComputation

then

The computation run after it.

TYPE: QiecComputation

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_sequence_computation".

TYPE: Literal['qiec_sequence_computation'] DEFAULT: 'qiec_sequence_computation'

QiecNatSort didactic-model

QiecNatSort(*, line: int = 0, col: int = 0, kind: Literal['qiec_nat_sort'] = 'qiec_nat_sort')

Bases: QiecIndexSort

The sort Nat of natural-number indices.

PARAMETER DESCRIPTION
line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_nat_sort".

TYPE: Literal['qiec_nat_sort'] DEFAULT: 'qiec_nat_sort'

QiecShapeIndex didactic-model

QiecShapeIndex(*, dimensions: tuple[QiecIndexExpr, ...] = (), line: int = 0, col: int = 0, kind: Literal['qiec_shape_index'] = 'qiec_shape_index')

Bases: QiecIndexExpr

A shape written as a bracketed list of dimensions.

PARAMETER DESCRIPTION
dimensions

The dimension indices, outermost first.

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

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_shape_index".

TYPE: Literal['qiec_shape_index'] DEFAULT: 'qiec_shape_index'

QiecShapeSort didactic-model

QiecShapeSort(*, rank: int | None = None, line: int = 0, col: int = 0, kind: Literal['qiec_shape_sort'] = 'qiec_shape_sort')

Bases: QiecIndexSort

The sort of shapes, of a fixed rank or of any rank.

PARAMETER DESCRIPTION
rank

The rank a shape must have, or None for any rank.

TYPE: int | None DEFAULT: None

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_shape_sort".

TYPE: Literal['qiec_shape_sort'] DEFAULT: 'qiec_shape_sort'

QiecTypeApplication didactic-model

QiecTypeApplication(*, constructor: str, static_arguments: tuple[QiecStaticArgument, ...] = (), indices: tuple[QiecIndexExpr, ...] = (), line: int = 0, col: int = 0, kind: Literal['qiec_type_application'] = 'qiec_type_application')

Bases: QiecTypeExpr

A type constructor applied to static arguments and indices.

PARAMETER DESCRIPTION
constructor

The constructor's name.

TYPE: str

static_arguments

The uniform type arguments, in order.

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

indices

The refinable index arguments, in order.

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

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_type_application".

TYPE: Literal['qiec_type_application'] DEFAULT: 'qiec_type_application'

QiecTypeBinder didactic-model

QiecTypeBinder(*, name: str, binder_kind: QiecKindExpr, line: int = 0, col: int = 0, kind: Literal['qiec_type_binder'] = 'qiec_type_binder')

Bases: QiecBinder

A telescope binder of kind Type or Effect.

PARAMETER DESCRIPTION
name

The binder's name.

TYPE: str

binder_kind

The kind the binder ranges over.

TYPE: QiecKindExpr

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_type_binder".

TYPE: Literal['qiec_type_binder'] DEFAULT: 'qiec_type_binder'

QiecTypeExpr didactic-model

QiecTypeExpr()

Bases: TaggedUnion

A value type in the QIEC source stratum.

QiecTypeKind didactic-model

QiecTypeKind(*, line: int = 0, col: int = 0, kind: Literal['qiec_type_kind'] = 'qiec_type_kind')

Bases: QiecKindExpr

The kind Type of value types.

PARAMETER DESCRIPTION
line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_type_kind".

TYPE: Literal['qiec_type_kind'] DEFAULT: 'qiec_type_kind'

QiecTypeName didactic-model

QiecTypeName(*, name: str, line: int = 0, col: int = 0, kind: Literal['qiec_type_name'] = 'qiec_type_name')

Bases: QiecTypeExpr

A reference to a type by name: a primitive, a binder, or a declared family without arguments.

PARAMETER DESCRIPTION
name

The type's name.

TYPE: str

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_type_name".

TYPE: Literal['qiec_type_name'] DEFAULT: 'qiec_type_name'

QiecUserIndexSort didactic-model

QiecUserIndexSort(*, name: str, line: int = 0, col: int = 0, kind: Literal['qiec_user_index_sort'] = 'qiec_user_index_sort')

Bases: QiecIndexSort

A reference to a user-declared closed index sort.

PARAMETER DESCRIPTION
name

The sort's name.

TYPE: str

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

kind

The discriminator; always "qiec_user_index_sort".

TYPE: Literal['qiec_user_index_sort'] DEFAULT: 'qiec_user_index_sort'

QiecValueParameter didactic-model

QiecValueParameter(*, name: str, type_expr: QiecTypeExpr, line: int = 0, col: int = 0)

Bases: Model

One typed value parameter of a computation declaration.

PARAMETER DESCRIPTION
name

The parameter's name.

TYPE: str

type_expr

The parameter's type.

TYPE: QiecTypeExpr

line

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

TYPE: int DEFAULT: 0

col

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

TYPE: int DEFAULT: 0

BinderArg didactic-model

BinderArg(*, arg: str, sort: str)

Bases: Model

An argument of a binder constructor; scoped arguments live in the extended context.

BinderDecl didactic-model

BinderDecl(*, name: str, binds: tuple[BinderVar, ...], scoped: tuple[BinderArg, ...], codomain: str, line: int = 0, col: int = 0)

Bases: Model

A binder constructor introducing new scoped variables.

BinderVar didactic-model

BinderVar(*, var: str, sort: str, annot: str | None = None, annot_sort: str | None = None)

Bases: Model

A variable introduced by a binder.

var and annot are names used for diagnostics only; references are by de-Bruijn index inside the scope. sort is the sort of the variable itself; annot_sort is the sort of the variable's type annotation, if one is supplied. When annot_sort is set, the binder constructor takes one additional positional argument (immediately preceding the bound variable's role in the scope) of that sort, which the encoder / decoder thread into Γ alongside the variable's embedding.

ConstructorDecl didactic-model

ConstructorDecl(*, name: str, domain: tuple[str, ...], codomain: str, line: int = 0, col: int = 0)

Bases: Model

A typed operation name : s_1, ..., s_n -> s in a signature.

EdgeKindDecl didactic-model

EdgeKindDecl(*, name: str, src: str, tgt: str, directed: bool = True, line: int = 0, col: int = 0)

Bases: Model

An edge kind in a graph-shaped signature.

directed is True for src -> tgt, False for src -- tgt.

EncoderInitRule didactic-model

EncoderInitRule(*, kind: str, arg: str, body: LetExprNode, line: int = 0, col: int = 0)

Bases: Model

Graph-signature initializer: maps vertex data payloads to initial vertex embeddings before message passing.

EncoderMessageRule didactic-model

EncoderMessageRule(*, edge_kind: str, src: str, tgt: str, body: LetExprNode, line: int = 0, col: int = 0)

Bases: Model

Graph-signature message: maps a (src, tgt) pair on an edge kind to a message vector.

EncoderRule didactic-model

EncoderRule(*, op: str, args: tuple[str, ...], body: LetExprNode, mode: Literal['plain', 'recurrent', 'attention'] = 'plain', state_var: str | None = None, prefix_var: str | None = None, line: int = 0, col: int = 0)

Bases: Model

A per-operation encoder function.

The body is a let-expression evaluated in an environment where the constructor arguments (as named in args) are bound to child vectors, plus framework-supplied helpers (ctx for binder contexts, state/prefix for recurrent / attention shapes).

mode selects sequence sugar:

  • "plain" for direct algebra-hom rule (default).
  • "recurrent" for left-fold, state carries the accumulator.
  • "attention" for prefix carries the running list of prior compressed children.

EncoderUpdateRule didactic-model

EncoderUpdateRule(*, vertex_kind: str, self_var: str, msgs_var: str, body: LetExprNode, line: int = 0, col: int = 0)

Bases: Model

Graph-signature update: maps (self_embed, aggregated_msgs) to the next vertex embedding, per vertex kind.

EncoderVarInit didactic-model

EncoderVarInit(*, var_sort: str, annot_sort: str | None = None, ty: str | None = None, body: LetExprNode, line: int = 0, col: int = 0)

Bases: Model

One var_init <var_sort> [from <annot_sort> [as <name>]] rule.

annot_sort=None is the unannotated-binder case (no type annotation; the body sees no extra arg). When annot_sort is set, ty is the body's parameter name bound to the annotation embedding.

SortDecl didactic-model

SortDecl(*, name: str, kind: Literal['object', 'index', 'data'], options: tuple[OptionEntry, ...] = (), line: int = 0, col: int = 0)

Bases: Model

One sort within a signature.

kind is one of "object", "index", "data". The surface form moves dim and vocab into the unified option block: s : data [dim=16, vocab=["a", "b"]]. The compiler reads them back out of options at elaboration time.

SortDim didactic-model

SortDim(*, sort: str, dim: int)

Bases: Model

A (sort, dim) association declared in a encoder/decoder.

SortVocabLiteral didactic-model

SortVocabLiteral(*, kind: Literal['string', 'integer', 'float'], text: str)

Bases: Model

One entry of a data sort's closed vocabulary.

The literal carries its surface text plus a tag so the compiler can decode each entry into the canonical Python value the runtime stores in Sort.vocab (str, int, or float).

VertexKindDecl didactic-model

VertexKindDecl(*, name: str, kind: Literal['object', 'index', 'data'], options: tuple[OptionEntry, ...] = (), line: int = 0, col: int = 0)

Bases: Model

A vertex kind in a graph-shaped signature.

Like SortDecl, the surface threads dim and any other modifier through the unified option block.

ContinuousConstructor didactic-model

ContinuousConstructor(*, constructor: Literal['Real', 'Simplex', 'Sphere', 'Ball', 'CholeskyFactor', 'Covariance', 'Correlation', 'Orthogonal', 'Stiefel', 'LowerTriangular', 'Diagonal'], args: tuple[str, ...] = (), kwargs: dict[str, float | int | str] = field(default_factory=dict), line: int = 0, col: int = 0, kind: Literal['continuous_constructor'] = 'continuous_constructor')

Bases: ObjectExpr

A continuous-space constructor call.

The eleven continuous constructors are: Real, Simplex, Sphere, Ball, CholeskyFactor, Covariance, Correlation, Orthogonal, Stiefel, LowerTriangular, Diagonal. The compiler dispatches on the constructor field to pick the appropriate quivers.continuous.spaces.ContinuousSpace subclass.

DiscreteConstructor didactic-model

DiscreteConstructor(*, constructor: Literal['FinSet'], args: tuple[str, ...] = (), kwargs: dict[str, float | int | str] = field(default_factory=dict), line: int = 0, col: int = 0, kind: Literal['discrete_constructor'] = 'discrete_constructor')

Bases: ObjectExpr

A discrete-type constructor call: currently FinSet(N).

ObjectCoproduct didactic-model

ObjectCoproduct(*, components: tuple[ObjectExpr, ...], line: int = 0, col: int = 0, kind: Literal['object_coproduct'] = 'object_coproduct')

Bases: ObjectExpr

Coproduct type: A + B.

ObjectEffectApply didactic-model

ObjectEffectApply(*, effect: str, args: tuple[ObjectExpr, ...], line: int = 0, col: int = 0, kind: Literal['object_effect_apply'] = 'object_effect_apply')

Bases: ObjectExpr

Effect-typed type-application: T(X).

The effect field names the effect (a previously-declared effect or stdlib effect); args are its applied arguments. Legal only inside a FreeResiduated whose effects list mentions the named effect.

ObjectExpr didactic-model

ObjectExpr()

Bases: TaggedUnion

Sum of type-expression node kinds.

TypeName didactic-model

TypeName(*, name: str, line: int = 0, col: int = 0, kind: Literal['type_name'] = 'type_name')

Bases: ObjectExpr

A named type reference (identifier or integer literal).

ObjectProduct didactic-model

ObjectProduct(*, components: tuple[ObjectExpr, ...], line: int = 0, col: int = 0, kind: Literal['object_product'] = 'object_product')

Bases: ObjectExpr

Product type: A * B.

ObjectSlash didactic-model

ObjectSlash(*, result: ObjectExpr, argument: ObjectExpr, direction: Literal['/', '\\'], line: int = 0, col: int = 0, kind: Literal['object_slash'] = 'object_slash')

Bases: ObjectExpr

Residuated slash type: result / argument or result \ argument.

Legal only when both operands inhabit a residuated universe (typically a FreeResiduated object). The compiler enforces this at use-site; the grammar accepts the slash on any pair of type expressions.

atom_to_draw_arg

atom_to_draw_arg(value: str | float | int | DrawArg) -> DrawArg

Lift a plain Python value into the DrawArg it denotes.

PARAMETER DESCRIPTION
value

A name, a number, or an argument that is already a DrawArg.

TYPE: str | float | int | DrawArg

RETURNS DESCRIPTION
DrawArg

A DrawArgName for a string, a DrawArgScalar for a number, and value itself for a DrawArg.

RAISES DESCRIPTION
TypeError

If value is none of the accepted kinds.

Source code in src/quivers/dsl/ast_nodes/program_steps.py
def atom_to_draw_arg(value: str | float | int | DrawArg) -> DrawArg:
    """Lift a plain Python value into the `DrawArg` it denotes.

    Parameters
    ----------
    value : str | float | int | DrawArg
        A name, a number, or an argument that is already a `DrawArg`.

    Returns
    -------
    DrawArg
        A `DrawArgName` for a string, a `DrawArgScalar` for a number,
        and ``value`` itself for a `DrawArg`.

    Raises
    ------
    TypeError
        If ``value`` is none of the accepted kinds.
    """
    if isinstance(value, DrawArg):
        return value
    if isinstance(value, str):
        return DrawArgName(text=value)
    if isinstance(value, (int, float)):
        return DrawArgScalar(value=float(value))
    raise TypeError(
        f"atom_to_draw_arg: expected str | float | DrawArg, got {type(value).__name__}"
    )