Host API Types Reference

Host API Types Reference

RillFieldDef

RillFieldDef describes a single field within a compound type. All four compound collection types use RillFieldDef to represent their element or field definitions.

interface RillFieldDef {
  name?: string;
  type: TypeStructure;
  defaultValue?: RillValue;
  annotations?: Record<string, RillValue>;
}
FieldTypeRequiredDescription
namestringNoField name. Present for dict, ordered, and fn params. Absent for positional tuple elements
typeTypeStructureYesStructural type of this field or element
defaultValueRillValueNoDefault value when the field is omitted. undefined = field is required. Detect presence with field.defaultValue !== undefined
annotationsRecord<string, RillValue>NoEvaluated annotation values keyed by annotation name. Property is absent when no annotations are declared

See TypeStructure for field access patterns per collection type.


TypeStructure

TypeStructure is a discriminated union that describes the structural shape of any rill value. The runtime uses it for type checking, type inference, and formatting.

type TypeStructure =
  | { kind: 'number' }
  | { kind: 'string' }
  | { kind: 'bool' }
  | { kind: 'datetime' }
  | { kind: 'duration' }
  | { kind: 'list'; element?: TypeStructure }
  | { kind: 'dict'; fields?: Record<string, RillFieldDef> }
  | { kind: 'tuple'; elements?: RillFieldDef[] }
  | { kind: 'ordered'; fields?: RillFieldDef[] }
  | { kind: 'map'; key?: TypeStructure; value?: TypeStructure }
  | { kind: 'vector'; dimensions: number }
  | { kind: 'fn'; params?: RillFieldDef[]; ret?: TypeStructure }
  | { kind: 'type'; typeName: string }
  | { kind: 'union'; members: TypeStructure[] }
  | { kind: 'literal'; value: string | number | boolean | RillAtomValue }
  | { kind: 'stream'; chunk?: TypeStructure; ret?: TypeStructure }
  | { kind: 'any' }
  | { kind: string; data?: unknown }; // catch-all for types without parameterized structure

The kind field is the discriminator. Leaf variants (number, string, bool, datetime, duration, any) carry no sub-fields. Compound variants carry their structural sub-fields.

Field Constraints

VariantFieldTypeSemantics
datetimeN/AN/ALeaf variant. No sub-fields
durationN/AN/ALeaf variant. No sub-fields
listelementTypeStructure | undefinedElement type for all list members. Absent when element type is unknown
dictfieldsRecord<string, RillFieldDef> | undefinedNamed fields with individual types and optional annotations. Present for structural dicts
tupleelementsRillFieldDef[] | undefinedOrdered positional fields. Index access: type.elements[i]
orderedfieldsRillFieldDef[] | undefinedNamed ordered fields. Index access: type.fields[i]. Present for structural ordered types
mapkeyTypeStructure | undefinedScalar key type shared by every key. Absent for the bare map type
mapvalueTypeStructure | undefinedValue type for all map values. Absent for the bare map type
vectordimensionsnumberEmbedding dimension count
typetypeNamestringName of the registered host type
unionmembersTypeStructure[]Member types in written order, after duplicate and subsumed members are dropped
literalvaluestring | number | boolean | RillAtomValueOne scalar value. Appears only inside union.members. The error_code type is a union of one atom literal per name in ERROR_CODES
fnparamsRillFieldDef[] | undefinedParameter definitions. Absent for the bare fn type
fnretTypeStructure | undefinedReturn type. Absent when return type is unspecified
streamchunkTypeStructure | undefinedOptional structural type of each chunk value
streamretTypeStructure | undefinedOptional structural type of the resolved return value

Annotation Access Patterns

Host applications read field annotations through the annotations property on RillFieldDef. The property is optional: absent when no annotations are declared. When present, it is a plain object, never null.

ContainerTypeStructure pathType
dict (structural)type.fields[fieldName].annotationsRecord<string, RillValue> | undefined
orderedtype.fields[index].annotationsRecord<string, RillValue> | undefined
tupletype.elements[index].annotationsRecord<string, RillValue> | undefined
fntype.params[index].annotationsRecord<string, RillValue> | undefined
// Reading annotations from a structural dict field
function getFieldDescription(
  type: TypeStructure & { kind: 'dict'; fields: Record<string, RillFieldDef> },
  fieldName: string
): string | undefined {
  const field = type.fields[fieldName];
  if (!field?.annotations) return undefined;
  const desc = field.annotations['description'];
  return typeof desc === 'string' ? desc : undefined;
}

Host Interop Shapes (toNativeValue)

toNativeValue() converts opaque rill types to plain JavaScript objects. Datetime and duration produce these shapes:

TypeNative ShapeFields
datetime{ unix: number, iso: string }unix: UTC ms since epoch. iso: ISO 8601 string
duration{ months: number, ms: number }months: calendar month count. ms: fixed milliseconds

Exports

// Structural type system
export type { TypeStructure, RillFieldDef, RillFieldDescriptor };
export {
  inferStructure,
  commonType,
  structureEquals,
  structureMatches,
  formatStructure,
  formatFieldKey,
  formatDefaultLiteral,
  buildFieldDescriptor,
  paramsToStructuralType,
  structureToTypeValue,
  serializeValue,
  copyValue,
  deserializeValue,
  isIterator,
};

// Atoms
export { resolveAtom, atomName };
export type { RillAtom, RillStatus, InvalidateMeta, InvalidMeta, TraceFrame };
export type { ExtensionFactoryCtx };

// Halt formatting
export { formatHalt };

Hosts cannot add atoms or error codes. See ExtensionFactoryCtx below and Error Handling for how extensions report domain failures.

inferStructure

inferStructure(value: RillValue): TypeStructure

Returns the structural type descriptor for any rill value. Primitive values return leaf variants. Compound values return their respective variants with sub-fields populated from the value’s actual structure. Callable values return { kind: 'fn' }.

Pure function. Result is a frozen object.

commonType

commonType(a: TypeStructure, b: TypeStructure): TypeStructure | null

Returns the most specific shared type for two TypeStructure values, or null when they share none. The runtime uses it while inferring a list’s element type. Callers keep both inputs as members of a union when it returns null.

Cascade order:

StepConditionResult
Any-narrowingEither input is { kind: 'any' }The other input
Different kindsTop-level kind values differnull
Structural matchstructureEquals(a, b) is truea
ListsBoth are listA list of the merged element types, or null when those share none
OtherAnything else that differs structurally, including differing dicts, ordereds, and tuplesnull
InputResult
number and stringnull
list(number) and list(string)null
dict(a: number) and dict(b: number)null
dict(a: number) and dict(a: string)null

Pure function, no side effects.

List Element Inference

inferStructure infers a list’s element type without halting on mixed elements. An empty list has element type any. The result is the set of maximal element types: a member that another member accepts is dropped, and differing dicts, ordereds, and tuples stay separate members. The set does not depend on element order or count. Mixed elements therefore yield a union, as in list[1, "a"], whose type is list(union(number, string)). list[dict[a: 1], dict[b: 2]] infers list(union(dict(a: number), dict(b: number))). See Type System for the script-level rules.

structureEquals

structureEquals(a: TypeStructure, b: TypeStructure): boolean

Compares two structural types for deep structural equality. Switches on the kind discriminator. Leaf variants compare by kind alone. Compound variants compare sub-fields recursively.

Pure function. Variants with different kind values always return false.

structureMatches

structureMatches(value: RillValue, type: TypeStructure): boolean

Checks if a value matches a structural type descriptor. Used by the :? runtime type check operator. A named dict descriptor is exact: a dict with a key the descriptor does not name does not match.

Type descriptorMatching behavior
{ kind: 'any' }Matches all values
Compound variantDeep structural match against sub-fields

Function parameter default compatibility:

Value param defaultValueType param defaultValueResult
PresentAbsentfalse (the type omits the default)
AbsentPresentfalse (missing contract)
PresentPresenttrue if values are deeply equal
AbsentAbsenttrue

Pure function.

formatStructure

formatStructure(type: TypeStructure): string

Formats a structural type descriptor as a human-readable string.

InputOutput
{ kind: 'number' }"number"
{ kind: 'string' }"string"
{ kind: 'bool' }"bool"
{ kind: 'any' }"any"
{ kind: 'list', element: { kind: 'number' } }"list(number)"
{ kind: 'dict', fields: { 'a b': { type: { kind: 'number' } } } }"dict(\"a b\": number)" (key not spelled as an identifier or reserved word, and true/false, quoted)
{ kind: 'fn', params: [{ name: 'x', type: { kind: 'number' } }] }"fn(x: number):any"
{ kind: 'fn' }"fn"
{ kind: 'tuple', elements: [{ type: { kind: 'number' } }] }"tuple(number)"

formatFieldKey

formatFieldKey(key: string): string

Formats a dict or ordered field key the way formatStructure prints it. A key spelled as a letter or _ followed by letters, digits, or _ prints bare, reserved words included. true, false, and every other key print as a quoted rill string, so the output parses back to the same key.

InputOutput
'name'name
'while'while
'true'"true"
'1'"1"
'a b'"a b"

formatDefaultLiteral

formatDefaultLiteral(value: RillValue): string | undefined

Returns the source text of a default value, or undefined when the value has no rill literal form. A value has one when it is a string, a finite number that prints without an exponent, a bool, an atom, or a list, dict, tuple, ordered, or map holding only such values. Datetime, duration, function, vector, iterator, stream, and type values have none. .signature, hover, getFunctions, error messages, and generateManifest print = <literal> through this rule and leave out a default for which it returns undefined.

InputOutput
'a'"a"
55
[1, 2]list[1, 2]
1e23undefined
a durationundefined

buildFieldDescriptor

buildFieldDescriptor(
  structuralType: TypeStructure & { kind: 'dict' },
  fieldName: string,
  location: SourceLocation
): RillFieldDescriptor

Builds a frozen RillFieldDescriptor for a named field within a structural dict type.

structuralType must narrow to { kind: 'dict' } at the call site. The field must exist in fields or RILL-R003 is thrown.

RillFieldDescriptor

RillFieldDescriptor carries the full RillFieldDef for a specific named field. The runtime produces descriptors when evaluating field-access expressions on typed dicts.

interface RillFieldDescriptor {
  readonly __rill_field_descriptor: true;
  readonly fieldName: string;
  readonly fieldType: RillFieldDef;
}
FieldTypeDescription
__rill_field_descriptortrueBrand field. Distinguishes descriptors from plain dicts
fieldNamestringName of the accessed field
fieldTypeRillFieldDefFull field definition including type and optional default

paramsToStructuralType

paramsToStructuralType(params: RillParam[]): TypeStructure

Builds a TypeStructure fn variant from a parameter list. Return type is always { kind: 'any' }. Result is a frozen object.

Param shapeMaps to
param.type definedThe TypeStructure from param.type
param.type undefined{ kind: 'any' }

structureToTypeValue

structureToTypeValue(type: TypeStructure): RillTypeValue

Converts a TypeStructure descriptor into the RillTypeValue runtime representation used in the RillFunction.returnType field.

import { structureToTypeValue } from '@rcrsr/rill';
import type { RillFunction } from '@rcrsr/rill';

const fn: RillFunction = {
  params: [{ name: 'text', type: { kind: 'string' }, defaultValue: undefined, annotations: {} }],
  fn: (args) => args.text,
  returnType: structureToTypeValue({ kind: 'string' }),
};

serializeValue

serializeValue(value: RillValue): unknown

Converts a rill value to a JSON-serializable representation. Delegates to TypeProtocol.serialize for host types when registered. Primitive and built-in compound types produce plain JS values.

deserializeValue

deserializeValue(data: unknown, typeName: string): RillValue

Restores a runtime value from serialized data. Looks up the named type’s TypeProtocol.deserialize function and applies it to data. Throws if the type is not registered or the protocol has no deserialize implementation.

copyValue

copyValue(value: RillValue): RillValue

Produces a deep copy of any rill value. Used internally for default value hydration and value isolation. Delegates to TypeProtocol for host types when registered.

isIterator

isIterator(value: RillValue): boolean

Returns true when value is a lazy rill iterator (produced by range, repeat, or similar). Use this to guard code that must not consume a sequence prematurely.


ExtensionFactoryCtx

ExtensionFactoryCtx is the factory-phase context passed as the second argument to async extension factories.

interface ExtensionFactoryCtx {
  readonly signal: AbortSignal;
}
MemberDescription
signalFires when the runtime disposes before the factory completes.

See Host API Reference for usage examples.


InvalidateMeta

InvalidateMeta is the metadata descriptor passed to ctx.invalidate and returned by the detector in ctx.catch.

interface InvalidateMeta {
  readonly code: string;
  readonly provider: string;
  raw?: Record<string, unknown>;
}
FieldTypeDescription
codestringCore error code name (e.g. "TIMEOUT"). ok or a name outside the core error set throws RILL-R084 at the call.
providerstringOrigin identifier for the failure (e.g. the extension name).
rawRecord<string, unknown>Optional provider-specific payload. A message key populates the display message.

InvalidMeta

InvalidMeta is the alias used by the detector callback in ctx.catch. It is identical to InvalidateMeta.

type InvalidMeta = InvalidateMeta;

RillAtom

RillAtom is a frozen handle identified by name. Compare atoms by name, not by reference.

interface RillAtom {
  readonly __rill_atom: true;
  readonly name: string;
}
FieldTypeDescription
namestringAtom name without the # sigil (e.g. "TIMEOUT")

Use atomName(atom) to retrieve the name string. Use resolveAtom(name) to build a handle from a well-formed name; it throws on a malformed one.

import { resolveAtom, atomName } from '@rcrsr/rill';

const atom = resolveAtom('TIMEOUT');
atomName(atom);  // "TIMEOUT"

RillStatus

RillStatus is the fixed-shape metadata sidecar attached to every RillValue. Valid values share one frozen empty-status singleton. Invalid values carry a populated clone.

interface RillStatus {
  readonly code: RillAtom;
  readonly message: string;
  readonly provider: string;
  readonly raw: Readonly<Record<string, RillValue>>;
  readonly trace: ReadonlyArray<TraceFrame>;
}
FieldTypeDescription
codeRillAtom#ok on a valid value; a member of error_code (a name in ERROR_CODES) on an invalid one.
messagestringHuman-readable description. "" on valid values.
providerstringOrigin identifier. "" on valid values.
rawRecord<string, RillValue>Provider-specific payload bag. Frozen empty object on valid values.
traceReadonlyArray<TraceFrame>Append-only trace chain. Empty on valid values.

TraceFrame

TraceFrame is one entry in the append-only trace chain on an invalid value. Frames record origin first, latest last.

interface TraceFrame {
  readonly site: string;
  readonly kind: 'host' | 'type' | 'access' | 'guard-caught' | 'guard-rethrow' | 'wrap';
  readonly fn: string;
  readonly wrapped: Readonly<Record<string, RillValue>>;
}
FieldTypeDescription
sitestringSource location in file.rill:line[:col] form. "" when location is unavailable.
kindTraceKindOne of the 6 normative kinds below.
fnstringHost function name, operator, or type op. "" when not applicable.
wrappedRecord<string, RillValue>Prior status dict on wrap frames. {} on all other kinds.

Kind values:

KindAppended when
hostExtension calls ctx.invalidate. First frame.
typeType assertion or conversion fails.
accessInvalid value is accessed via pipe, method, or encode.
guard-caughtA guard block catches the halt.
guard-rethrowA caught invalid value is re-accessed and halts again.
wraperror "..." wraps an invalid value. wrapped carries prior status.

TypeDefinition

TypeDefinition is the registration contract for host-provided types. Pass instances to registerType when configuring the runtime.

interface TypeDefinition {
  name: string;
  identity: (v: RillValue) => boolean;
  isLeaf: boolean;
  immutable: boolean;
  methods: Record<string, RillFunction>;
  protocol: TypeProtocol;
}
FieldTypeRequiredDescription
namestringYesUnique type name. Appears in error messages and TypeStructure descriptors
identity(v: RillValue) => booleanYesReturns true when v is an instance of this type
isLeafbooleanYestrue = type has no sub-structure. false = type may carry fields
immutablebooleanYestrue = values of this type are immutable after construction
methodsRecord<string, RillFunction>YesMethod functions accessible via .methodName on type instances
protocolTypeProtocolYesBehavioral protocol for formatting, equality, comparison, and serialization
import type { TypeDefinition, TypeProtocol } from '@rcrsr/rill';
import { structureToTypeValue } from '@rcrsr/rill';

const dateType: TypeDefinition = {
  name: 'date',
  identity: (v) => v instanceof Date,
  isLeaf: true,
  immutable: true,
  methods: {
    format: {
      params: [{ name: 'pattern', type: { kind: 'string' }, defaultValue: undefined, annotations: {} }],
      fn: (args) => (args.$self as Date).toLocaleDateString(),
      returnType: structureToTypeValue({ kind: 'string' }),
    },
  },
  protocol: {
    format: (v) => (v as Date).toISOString(),
    serialize: (v) => (v as Date).toISOString(),
    deserialize: (data) => new Date(data as string),
  },
};

TypeProtocol

TypeProtocol defines behavioral contracts for a registered host type. All fields are optional except format.

interface TypeProtocol {
  format: (v: RillValue) => string;
  structure?: (v: RillValue) => TypeStructure;
  eq?: (a: RillValue, b: RillValue) => boolean;
  compare?: (a: RillValue, b: RillValue) => number;
  convertTo?: Record<string, (v: RillValue) => RillValue>;
  serialize?: (v: RillValue) => unknown;
  deserialize?: (data: unknown) => RillValue;
}
FieldTypeRequiredDescription
format(v: RillValue) => stringYesReturns the display string for a value. Used in log, string interpolation, and error messages
structure(v: RillValue) => TypeStructureNoReturns the structural descriptor for a value. Absent = type has no parameterized structure
eq(a: RillValue, b: RillValue) => booleanNoEquality test. Absent = identity comparison (===)
compare(a: RillValue, b: RillValue) => numberNoOrdering: negative, zero, or positive. Absent = type is unordered; > and < raise RILL-R002
convertToRecord<string, (v: RillValue) => RillValue>NoExplicit conversion targets for the -> type operator. Keys are target type names
serialize(v: RillValue) => unknownNoConverts value to JSON-serializable form. Used by serializeValue
deserialize(data: unknown) => RillValueNoRestores value from serialized data. Used by deserializeValue
import type { TypeProtocol } from '@rcrsr/rill';

const dateProtocol: TypeProtocol = {
  format: (v) => (v as Date).toISOString(),
  eq: (a, b) => (a as Date).getTime() === (b as Date).getTime(),
  compare: (a, b) => (a as Date).getTime() - (b as Date).getTime(),
  serialize: (v) => (v as Date).toISOString(),
  deserialize: (data) => new Date(data as string),
};

AST Node Types

AST node types are exported from @rcrsr/rill for tools that walk parsed scripts (linters, analyzers, codegen). The full list of node names ships in index.ts; this section documents nodes whose shape includes metadata not obvious from their name.

DictEntryNode

interface DictEntryNode {
  readonly type: 'DictEntry';
  readonly key:
    | string
    | ListLiteralNode
    | DictKeyVariable
    | DictKeyComputed;
  readonly value: ExpressionNode;
  readonly keyForm?: 'identifier' | 'string' | 'number' | 'bool';
  // ...standard BaseNode span/location fields
}

keyForm records how a string key appeared in source. A single number or bool key is stored as the string of its spelling; a multi-key list element must already be a string:

Source formkeyForm
dict[name: 1] (bare identifier)'identifier'
dict["name": 1] (quoted string)'string'
dict[1: "x"] (number, stored as "1")'number'
dict[true: "x"] (boolean, stored as "true")'bool'
Computed, variable, or list keysundefined
Internal '...' spread sentinelundefined

keyForm is parser metadata only. Runtime semantics are unchanged: dict[a: 1] and dict["a": 1] are AST- and value-equal. Use keyForm in linting and analysis tools that want to tell bare identifier, quoted, number, and bool keys apart, for example to treat quoted keys as an intentional escape for foreign API names (for example a snake_case rule that allows dict["maxResults": ...] while flagging dict[maxResults: ...]).

RecoveryErrorNode

interface RecoveryErrorNode {
  readonly type: 'RecoveryError';
  readonly span: SourceSpan;
  readonly message: string;
  readonly text: string;
}

RecoveryErrorNode represents an opaque span of source text the parser could not interpret during error recovery. It carries no internal structure, only the raw text and a description of the failure. It only appears in ASTs produced by parsing with recoveryMode: true.

FieldPurpose
spanCovers the skipped text’s token range; non-empty
messageHuman-readable description of what went wrong
textThe raw source text that could not be parsed

PartialExpressionNode

interface PartialExpressionNode {
  readonly type: 'PartialExpression';
  readonly span: SourceSpan;
  readonly message: string;
  readonly children: readonly ExpressionNode[];
}

PartialExpressionNode represents a partially-typed expression captured during parser error recovery. It is a structured fragment where at least one child parsed successfully, even though the overall expression did not. It is a member of the ExpressionNode and script statements unions, so existing AST walkers reach it without additional type-narrowing.

FieldPurpose
spanCovers the partial fragment’s token range; non-empty
messageHuman-readable description of what the parser expected
childrenTyped child nodes recognized within the fragment; always at least one entry, each with its own non-empty span

PartialExpressionNode is kept distinct from RecoveryErrorNode so the two recovery shapes never collide in downstream visitors. RecoveryErrorNode covers opaque skipped text with no internal structure. PartialExpressionNode preserves the child nodes the parser did recognize. Both node types only appear in ASTs produced by parsing with recoveryMode: true.

AST visitor callback shape

type AstVisitor = (node: ASTNode) => void;

function walkAst(root: ASTNode, visit: AstVisitor): void;
FieldBehavior
nodeEach ASTNode union member reachable from root, in pre-order
Call orderParent nodes are visited before their children
CoverageEvery union member, including RecoveryErrorNode and PartialExpressionNode

Every member of the ASTNode union has a defined child set: a fixed, exhaustively-checked list of the ASTNodes nested directly inside it. walkAst uses this per-node-type contract to reach every reachable node, so a visitor callback never skips a branch of the tree. Field-access and dict-key segments are not ASTNode union members; see Field access and dict key spans for how their nested nodes are reached instead.

Field access and dict key spans

FieldAccessLiteral, FieldAccessVariable, DictKeyVariable, and DictKeyComputed each carry a readonly span: SourceSpan field, following the same inline-span pattern as BracketAccess. These interfaces are segments within a larger node (a property access chain or a dict key) rather than standalone BaseNode subtypes, so span covers only that segment.

interface FieldAccessLiteral {
  readonly kind: 'literal';
  readonly field: string;
  readonly span: SourceSpan;
}

interface FieldAccessVariable {
  readonly kind: 'variable';
  readonly variableName: string | null;
  readonly span: SourceSpan;
}

interface DictKeyVariable {
  readonly kind: 'variable';
  readonly variableName: string;
  readonly span: SourceSpan;
}

interface DictKeyComputed {
  readonly kind: 'computed';
  readonly expression: ExpressionNode;
  readonly span: SourceSpan;
}
Interfacespan boundary
FieldAccessLiteralFrom the . token through the field-name token, e.g. .name
FieldAccessVariableFrom the . token through the variable-name token, e.g. .$var
DictKeyVariableFrom the opening key delimiter through the closing delimiter
DictKeyComputedFrom the opening key delimiter through the closing delimiter

Each span covers only its own segment, not the containing expression’s full range. For $data.name, the FieldAccessLiteral span covers .name, not $data.name. Use these spans for precise error highlighting or source-map generation on individual access segments within a chain.


See Also


Migration: 0.18.0 Renamed Exports

v0.18.0 renames 7 exports in @rcrsr/rill to remove the rill-prefixed naming convention and align with the TypeStructure terminology introduced in v0.17.0. All old names are removed; update imports before upgrading.

Symbol Mapping Table

Old NameNew NameImport Change
RillTypeTypeStructureimport type { TypeStructure } from '@rcrsr/rill'
formatStructuralTypeformatStructureimport { formatStructure } from '@rcrsr/rill'
inferStructuralTypeinferStructureimport { inferStructure } from '@rcrsr/rill'
structuralTypeEqualsstructureEqualsimport { structureEquals } from '@rcrsr/rill'
structuralTypeMatchesstructureMatchesimport { structureMatches } from '@rcrsr/rill'
isRillIteratorisIteratorimport { isIterator } from '@rcrsr/rill'
rillTypeToTypeValuestructureToTypeValueimport { structureToTypeValue } from '@rcrsr/rill'

Codemod

No automated codemod is available for this rename. Use find-and-replace across your codebase for each old name. The old names do not exist in v0.18.0; TypeScript will report errors at every import site, making all affected locations visible before runtime.