<!-- https://epsil.dev/compute-engine/api/ -->

# Compute Engine API Reference

import APIFilter from '@site/src/components/APIFilter';
import MemberCard from '@site/src/components/MemberCard';

# Compute Engine API Reference



## Compute Engine

<MemberCard>

### AngularUnit {#angularunit}

```ts
type AngularUnit = "rad" | "deg" | "grad" | "turn";
```

When a unitless value is passed to or returned from a trigonometric function,
the angular unit of the value.

| Angular Unit | Description |
|:--------------|:-------------|
| `rad` | radians, 2π radians is a full circle |
| `deg` | degrees, 360 degrees is a full circle |
| `grad` | gradians, 400 gradians is a full circle |
| `turn` | turns, 1 turn is a full circle |

To change the angular unit used by the Compute Engine, use:

```js
ce.angularUnit = 'deg';
```

</MemberCard>

<MemberCard>

### RoundingTies {#roundingties}

```ts
type RoundingTies = 
  | "away-from-zero"
  | "to-even"
  | "toward-zero"
  | "toward-positive-infinity"
  | "toward-negative-infinity";
```

The rule that `Round` uses for a value that is exactly halfway between two
integers (a tie). A value that is not a tie always rounds to the nearest
integer.

| Rule | `Round(2.5)` | `Round(3.5)` | `Round(-2.5)` | Description |
|:-----|:------------:|:------------:|:-------------:|:------------|
| `away-from-zero` | `3` | `4` | `-3` | the default |
| `to-even` | `2` | `4` | `-2` | IEEE 754, Python, NumPy and Mathematica |
| `toward-zero` | `2` | `3` | `-2` | |
| `toward-positive-infinity` | `3` | `4` | `-2` | JavaScript `Math.round` |
| `toward-negative-infinity` | `2` | `3` | `-3` | |

The rule also applies to the step form `Round(x, step)`, which rounds to
the nearest multiple of the step: the tie is at the half of the step
(with the step `1/100`, `Round(0.125, 1/100)` is a tie).

To change the rule used by the Compute Engine, use:

```js
ce.roundingTies = 'to-even';
```

</MemberCard>

<MemberCard>

### AssignValue {#assignvalue}

```ts
type AssignValue = KernelAssignValue<Expression, ExpressionInput, IComputeEngine>;
```

Assignable value for `ce.assign()`.

</MemberCard>

### ComputeEngine {#computeengine}

Compute engine surface used by the expression and definition types.

This interface is empty here and augmented by `types-engine.ts` with the
members of `IComputeEngine`. The expression types cannot import
`IComputeEngine` directly: `types-engine.ts` imports this file, and the
repository allows no import cycle, not even between type-only modules.
`types-definitions.ts` imports this interface from here for the same
reason. The package entry points export their own `ComputeEngine` type
(`IComputeEngine`), which takes precedence over this one; the two are
structurally identical.

#### Extends

- [`IComputeEngine`](#icomputeengine)

<MemberCard>

##### ComputeEngine.latexSyntax {#latexsyntax-1}

```ts
readonly latexSyntax: ILatexSyntax | undefined;
```

The LatexSyntax instance used for LaTeX parsing/serialization.
 `undefined` when no LatexSyntax was provided to the constructor and
 the entry point has no LaTeX support (the core-only bundle).

 To add a notation to a running engine, call
 `ce.latexSyntax.addEntries([...])`: later parses and serializations use
 the new entries. An engine created without the `latexSyntax` option
 has its own instance, so the change applies to that engine only. An
 instance given to several engines with the `latexSyntax` option is
 shared: the change applies to all of them.

</MemberCard>

<MemberCard>

##### ComputeEngine.latexOptions {#latexoptions-1}

```ts
latexOptions: Partial<ParseLatexOptions & SerializeLatexOptions>;
```

Engine-wide LaTeX parse/serialize options (e.g. `decimalSeparator`).
 Merged into every `parse()` and `toLatex()` call between LatexSyntax
 defaults and per-call overrides.

</MemberCard>

<MemberCard>

##### ComputeEngine.True {#true-1}

```ts
readonly True: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.False {#false-1}

```ts
readonly False: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.Pi {#pi-1}

```ts
readonly Pi: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.E {#e-1}

```ts
readonly E: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.Nothing {#nothing-1}

```ts
readonly Nothing: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.Missing {#missing-1}

```ts
readonly Missing: Expression;
```

The `Missing` symbol: an absent value whose position is preserved.

</MemberCard>

<MemberCard>

##### ComputeEngine.Zero {#zero-1}

```ts
readonly Zero: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.One {#one-1}

```ts
readonly One: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.Half {#half-1}

```ts
readonly Half: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.NegativeOne {#negativeone-1}

```ts
readonly NegativeOne: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.Two {#two-1}

```ts
readonly Two: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.I {#i-1}

```ts
readonly I: Expression;
```

ImaginaryUnit

</MemberCard>

<MemberCard>

##### ComputeEngine.NaN {#nan-2}

```ts
readonly NaN: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.PositiveInfinity {#positiveinfinity-2}

```ts
readonly PositiveInfinity: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.NegativeInfinity {#negativeinfinity-2}

```ts
readonly NegativeInfinity: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.ComplexInfinity {#complexinfinity-1}

```ts
readonly ComplexInfinity: Expression;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.context {#context-1}

```ts
readonly context: EvalContext;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.contextStack {#contextstack-1}

```ts
contextStack: readonly EvalContext[];
```

</MemberCard>

<MemberCard>

##### ComputeEngine.\_delegatedEvaluations {#_delegatedevaluations-1}

```ts
_delegatedEvaluations: number;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.macroNames {#macronames-1}

```ts
readonly macroNames: ReadonlySet<string>;
```

The names that were declared as a macro on this engine
(`ce.declare(name, { macro })`), in any scope. The set never shrinks: a
name stays in it after the scope of its declaration is popped, and after
a later declaration of the name that is not a macro. So a name that is
not in the set is not a macro in any scope, and a name that is in the set
may be one: `ce.lookupDefinition(name)` gives the definition that the
current scope reads. The set of an engine with no macro is empty.

</MemberCard>

<MemberCard>

##### ComputeEngine.timeRemaining {#timeremaining-1}

```ts
readonly timeRemaining: number;
```

The number of milliseconds left before the earliest deadline of the
active `withTimeLimit` spans (an enclosing span preempts a later inner
limit), and `0` or less once that deadline has passed. `Infinity` when
no active span has a time limit, which includes a `withStepBudget` span
with no `withTimeLimit` around it.

This value and [stepBudgetSpent](#stepbudgetspent-1) describe the span that is active
in the current synchronous code. Code that runs after an `await`, even
inside `withTimeLimit` or an `evaluateAsync()` call, is outside the
span: it reads `Infinity` and `false`.

The engine checks its deadline only inside its own work (evaluation,
canonicalization). A host loop that runs inside a span and does work of
its own (walking expressions, building a list) reads this value to stop
on time: `if (ce.timeRemaining <= 0) break;`.

A spent step budget does not change this value; read
[stepBudgetSpent](#stepbudgetspent-1) for it.

</MemberCard>

<MemberCard>

##### ComputeEngine.stepBudgetSpent {#stepbudgetspent-1}

```ts
readonly stepBudgetSpent: boolean;
```

True inside a `withStepBudget` span (or a span nested in one) when a
step budget of the current span or of an enclosing one is spent; false
otherwise, and always false outside any span.

When a budget is spent, the engine throws a `CancellationError`, but
code between the throw and the end of the span can catch it and return
a value. Such a value is partial. A host that stores values in a cache
reads this before a write, so that it does not keep a partial value.

</MemberCard>

<MemberCard>

##### ComputeEngine.stepsLeft {#stepsleft-1}

```ts
readonly stepsLeft: number | undefined;
```

The number of steps left in the budget of the innermost
`withStepBudget` span, or `undefined` when no such span is active.
It is negative once that budget is spent: after the throw that spends
it, each later check still counts one step, so `steps - ce.stepsLeft`
is the number of steps used only while the budget is not spent. A
`withTimeLimit` span nested in a step-budget span does not change it,
nor does a budget the engine opens for its own search: host code that
the engine calls during that search reads the host's budget.

Read inside the callback of `withStepBudget`, it tells the two things
[stepBudgetSpent](#stepbudgetspent-1) cannot: how many steps the span has used
(`steps - ce.stepsLeft`), and whether THIS span's budget is spent
(`ce.stepsLeft < 0`) rather than the budget of an enclosing span. A
step is an opaque unit: compare counts only on one engine version.
Like [timeRemaining](#timeremaining-1), it describes the span of the current
synchronous code.

</MemberCard>

<MemberCard>

##### ComputeEngine.iterationLimit {#iterationlimit-1}

```ts
iterationLimit: number;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.recursionLimit {#recursionlimit-1}

```ts
recursionLimit: number;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.maxCollectionSize {#maxcollectionsize-1}

```ts
maxCollectionSize: number;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.bignum {#bignum-2}

```ts
bignum: (a) => BigDecimal;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.complex {#complex-2}

```ts
complex: (a, b?) => Complex;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.angularUnit {#angularunit-2}

```ts
angularUnit: AngularUnit;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.roundingTies {#roundingties-2}

```ts
roundingTies: RoundingTies;
```

The rule that `Round` uses for a value halfway between two integers.
 See [RoundingTies](#roundingties). Default: `'away-from-zero'`.

</MemberCard>

<MemberCard>

##### ComputeEngine.costFunction {#costfunction-2}

```ts
costFunction: (expr) => number;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.simplificationRules {#simplificationrules-1}

```ts
simplificationRules: Rule[];
```

The rules used by `.simplify()` when no explicit `rules` option is passed.
 Initialized to the built-in simplification rules.
 Users can `push()` additional rules or replace the entire array.

</MemberCard>

<MemberCard>

##### ComputeEngine.solveRules {#solverules-1}

```ts
solveRules: Rule[];
```

The rules used by `solve()` to find roots of univariate expressions.
 Each rule matches a normalized equation `f(_x) = 0` — the unknown is
 the wildcard `_x` — and `replace` produces a root expression.
 Conditions should reject matches where other wildcards capture `_x`.
 Candidate roots are validated against the original equation, so an
 over-eager template degrades to a no-op rather than a wrong answer.
 Initialized to the built-in root-finding rules; `push()` to extend,
 assign to replace.

</MemberCard>

<MemberCard>

##### ComputeEngine.harmonizationRules {#harmonizationrules-1}

```ts
harmonizationRules: Rule[];
```

The rules used by `solve()` to transform an equation into equivalent,
 easier-to-solve forms before root-finding (e.g. `ln f(x) → f(x) - 1`).
 Same conventions and extension pattern as `solveRules`.

</MemberCard>

<MemberCard>

##### ComputeEngine.strict {#strict-2}

```ts
strict: boolean;
```

</MemberCard>

<MemberCard>

##### ComputeEngine.jit {#jit-1}

```ts
jit: "auto" | "off";
```

Whether the engine may implicitly generate and execute compiled code as
a performance optimization (auto-compiled `Map` drains, compiled numeric
quadrature/limit kernels). `'auto'` (default) attempts implicit
compilation and latches to `'off'` engine-wide on the first CSP
`EvalError`; `'off'` never attempts it. Explicit `compile()` is exempt.

</MemberCard>

<MemberCard>

##### ComputeEngine.workers {#workers-1}

```ts
workers: KernelPool | undefined;
```

The worker pool that `broadcastAsync()` of a compiled result uses, built
by the host with `createKernelPool()`. The engine creates no worker on
its own: with no pool every batch runs on the calling thread. One pool
can serve several engines, and it is read at each call.

</MemberCard>

<MemberCard>

##### ComputeEngine.arrayAllocation {#arrayallocation-1}

```ts
arrayAllocation: ((count, bytesPerCell) => boolean) | undefined;
```

The permission to allocate the storage of a mutable array, asked once
by `ArrayFrom` when the count of cells is known and before the engine
allocates the storage. `bytesPerCell` is the size of one cell: 1, 2, 4
or 8 for a machine cell, 4 for a tuple cell, 8 for an expression cell.
A result of `false`, an exception thrown by the function, and a failure
of the JavaScript allocation give the error `array-allocation-refused`.
It is a permission: the engine reports no release. It is not called for
the storage of an array that the host gives. With no function, the
engine refuses a storage of more than 2 GiB (2^31 bytes) for one array.

</MemberCard>

<MemberCard>

##### ComputeEngine.arrayCreated {#arraycreated-1}

```ts
arrayCreated: ((array) => void) | undefined;
```

A function called with each array that `ArrayFrom` made, after the
construction succeeded: not for a construction that failed, and not for
an array that the host made with [array](#array). The prelude code that
makes a raster gives the host no other reference to it, so a host that
limits the bytes alive holds a weak reference to each array here:

```ts
const alive = new Set<WeakRef<object>>();
ce.arrayCreated = (array) => alive.add(new WeakRef(array));
```

The engine does not catch an exception that the function throws: it
propagates out of the evaluation. A `TypeError`, a `RangeError` and a
`ReferenceError` are the exception: as from the handler of any
operator, they become the error `internal-error` of `ArrayFrom`.

</MemberCard>

<MemberCard>

##### ComputeEngine.trace {#trace-1}

```ts
trace: readonly string[];
```

A list of the function calls to the current evaluation context

</MemberCard>

<MemberCard>

##### ComputeEngine.effects {#effects-3}

```ts
get effects(): EffectHandlers
set effects(handlers: EffectHandlerOverrides): void
```

The host capabilities of this engine: the handlers the library operators
use to reach the host. `Print` and `Input` use `effects.console`.

The registry is an immutable object. Reading returns the registry that a
new evaluation would use. Assigning installs a new registry: the assigned
object is a COMPLETE description — a handler it does not mention returns
to its default, so `ce.effects = {}` restores every default. A `null`
handler denies the capability: an operator that needs it evaluates to an
`Error("capability-denied", …)` value.

```ts
const lines: string[] = [];
ce.effects = {
  console: { log: (line) => lines.push(line), readLine: () => undefined },
};
```

Each evaluation (`evaluate()`, `N()`, `evaluateAsync()`) uses the registry
that was installed when it started. An assignment does not change the
handlers of an evaluation that is already running.

For a change that must last for one block of code only, use
[`withEffects`](#witheffects).

</MemberCard>

<MemberCard>

##### ComputeEngine.precision {#precision-2}

```ts
get precision(): number
set precision(p: number | "auto" | "machine"): void
```

</MemberCard>

<MemberCard>

##### ComputeEngine.tolerance {#tolerance-3}

```ts
get tolerance(): number
set tolerance(v: number | "auto"): void
```

The absolute tolerance of `chop()`, of `.is()`, of `ApproxEqual` and of
the numeric algorithms (the residual test of `Solve`). The comparison
operators and the methods `.isEqual()`, `.isLess()` and the others do
not use it: they compare two numbers exactly, at the working precision.
A number is kept as set; `'auto'` is `10^(-precision + 2)`, recomputed
at each precision change.

</MemberCard>

<MemberCard>

##### ComputeEngine.declareProtocol() {#declareprotocol-1}

```ts
declareProtocol(name, members, options?): void
```

Declare a protocol (Appendix A "Host API"). Throws on error, including
on re-declaration — the Epsil statement route replaces instead (P5).

`options.extends` lists the PARENTS of the protocol, protocols that must
already be declared:

```js
ce.declareProtocol('PartialOrder', {
  functions: { compare: '(self: Self, other: Self) -> integer' },
});
ce.declareProtocol('LinearOrder', {}, { extends: ['PartialOrder'] });
```

A type that conforms to `LinearOrder` then conforms to `PartialOrder`
too: a conformance to a protocol registers a conformance to each of its
ancestors that the type does not already conform to, and the
implementation given to `declareProtocolImplementation` may implement
the members of every ancestor. A protocol may not declare a member that
one of its ancestors declares (`protocol-member-inherited`), and two
parents whose ancestors declare the same member name cannot be extended
together (`protocol-extends-member-conflict`). An `extends` value that is
not an array of strings, or that lists a name twice, throws
`invalid-protocol-declaration`; a name that is not a declared protocol
throws `protocol-unknown`.

`options.description` documents the protocol, and
`options.memberDescriptions` its members, by name (markdown): an editor
shows them in the hover of the protocol and in the help of a member.

####### name

`string`

####### members

[`ProtocolMembersInput`](#protocolmembersinput)

####### options?

####### extends?

readonly `string`[]

####### description?

`string`

####### memberDescriptions?

`Readonly`\<`Record`\<`string`, `string`\>\>

</MemberCard>

<MemberCard>

##### ComputeEngine.declareProtocolImplementation() {#declareprotocolimplementation-1}

```ts
declareProtocolImplementation(
   type, 
   protocol, 
   impl, 
   options?): void
```

Implement `protocol` for `type`, declaring the conformance edge if it is
not already registered (Appendix A "Host API").

THROWS on every error — the host channel; the Epsil statement route
returns error VALUES instead. A second host implementation of the same
(type, protocol) pair throws rather than replacing (P5).

The callbacks are JavaScript functions, so they carry no signature the
engine can check: they are trusted like host-declared operator handlers,
and only member-name coverage, unknown members and a `set` handler on a
`readonly` property are validated.

`options.where` declares a CONDITIONAL conformance: `type` is then a HEAD
PATTERN naming the variables (`'list<T>'`) and `where` is the clause SOURCE
that binds them (`'where T is Comparable'`; the `where` word may be
omitted). A malformed clause, or a head variable the clause does not bind,
throws.

####### type

`string`

####### protocol

`string`

####### impl

[`ProtocolImplementationInput`](#protocolimplementationinput)

####### options?

####### where?

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.conformsTo() {#conformsto-1}

```ts
conformsTo(type, protocol): boolean
```

Whether `type` conforms to `protocol`, answered without calling any of
the protocol's members. An unknown protocol answers `false`.

Inheritance included: a conformance registered for a supertype answers
for its subtypes. A CONDITIONAL conformance (`list<T> is P where T is
P`) recurses, deciding itself against `type`'s own arguments.

`type` may be a `TypeString`, parsed the way [IComputeEngine.type](#type-10)
parses one.

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)

####### protocol

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.withTimeLimit() {#withtimelimit-1}

```ts
withTimeLimit<T>(limit, fn): T
```

Run `fn` with at most `ms` milliseconds (numeric form) or `limit.ms`
(object form, which also accepts an attribution `label`). A tighter
enclosing span preempts this limit; use the label and
`CancellationError.attribution`/`spans` to tell which limit fired.

**⚠️ `fn` MUST be synchronous.** The span is restored in a synchronous
`finally`, so a `Promise`-returning (`async`) callback hands control back
at its first `await` while the span is still open: work that resumes after
that point runs **outside** the deadline and is never cancelled (see
`docs/TIMEOUT-MODEL.md` §6.4). An `expr.evaluateAsync()` call that `fn`
makes before its first `await` is the exception: the evaluation keeps
the span's deadline until it ends
(`ce.withTimeLimit(20, () => { p = expr.evaluateAsync(); })`). For
cancellation that is not a time limit, use
`expr.evaluateAsync({ signal })` with an `AbortSignal`.

• T

####### limit

  \| `number`
  \| \{
  `ms`: `number`;
  `label`: `string`;
 \}

####### fn

() => `T` *extends* `Promise`\<`unknown`\> ? `never` : `T`

</MemberCard>

<MemberCard>

##### ComputeEngine.withStepBudget() {#withstepbudget-1}

```ts
withStepBudget<T>(limit, fn): T
```

Run `fn` with at most `limit.steps` steps of engine work: a hang guard
that fires at the same point on every machine, unlike a wall-clock
limit. A step is one of the engine's cooperative cancellation checks —
an opaque unit, deterministic for one computation on one engine state,
but not a measure of cost and not comparable across engine versions;
tune the budget empirically and keep a `withTimeLimit` span outside it.
A spent budget throws a `CancellationError` with `cause: 'step-budget'`
and the span's `label` as its `attribution`.

**⚠️ `fn` MUST be synchronous**, as for `withTimeLimit`.

• T

####### limit

####### steps

`number`

####### label?

`string`

####### fn

() => `T` *extends* `Promise`\<`unknown`\> ? `never` : `T`

</MemberCard>

<MemberCard>

##### ComputeEngine.withEffects() {#witheffects-1}

```ts
withEffects<T>(overrides, fn): T
```

Run `fn` with some host capabilities replaced or denied, then put the
previous ones back. Evaluations that START inside `fn` use the changed
registry.

`overrides` is applied on top of the registry in effect when
`withEffects` is called, so calls nest: a capability an inner call does
not mention keeps the handler of the outer call. A `null` value denies the
capability, even if it has a default handler — this is how to evaluate an
expression that is not trusted:

```ts
const result = ce.withEffects({ console: null }, () => expr.evaluate());
```

The previous registry is put back when `fn` returns or throws. If `fn`
returns a promise, it is put back when that promise settles (fulfilled or
rejected), and `withEffects` returns a promise that settles the same way.

An asynchronous evaluation keeps the registry it started with, so an
evaluation that started BEFORE `withEffects` was called is not changed by
it. But while the promise of an asynchronous `fn` is pending, the changed
registry is the installed one: an unrelated evaluation that starts during
that time, from other code, also uses it. Start such evaluations before
calling `withEffects`, or use a separate engine.

• T

####### overrides

[`EffectHandlerOverrides`](#effecthandleroverrides)

####### fn

() => `T`

</MemberCard>

<MemberCard>

##### ComputeEngine.withEvaluationContext() {#withevaluationcontext-1}

```ts
withEvaluationContext<T>(options, fn): T
```

Run the synchronous `fn` in the evaluation context that `options`
carries, then put the previous context back, and return the result of
`fn`.

For an `evaluateAsync` handler. The handler receives `options`, which
carry the evaluation context of the evaluation that called it: the host
capability registry, and the lexical scopes of the scoped operators that
the evaluation is inside (the scope of the index of a `Sum`, for
example). While the handler is suspended at an `await`, other code can
run on the same engine, so the engine does not keep that context
installed for the handler. Before the first `await`, the context is in
place. After it, synchronous work that reads the scope — canonicalizing
a held operand (`x.canonical`), `ce.box()`, `ce.parse()`, `evaluate()`,
`ce.assign()` — sees the global scope unless it runs inside `fn`. An
index of an enclosing `Sum` then stays symbolic, and a new global
symbol with its name is declared.

```ts
ce.declare('Late', {
  signature: '(integer) -> integer',
  lazy: true,
  evaluateAsync: async ([x], options) => {
    await delay(1);
    return ce
      .withEvaluationContext(options, () => x.canonical)
      .evaluateAsync(options);
  },
});
```

A nested `evaluateAsync(options)` call does not need it: the options
carry the context to that evaluation.

If `fn` returns a promise, only the synchronous part of `fn`, up to its
first `await`, runs in the context.

• T

####### options

`Partial`\<`EvaluateOptions`\> \| `undefined`

####### fn

() => `T`

</MemberCard>

<MemberCard>

##### ComputeEngine.chop() {#chop-1}

###### chop(n)

```ts
chop(n): number
```

####### n

`number`

###### chop(n)

```ts
chop(n): 0 | BigDecimal
```

####### n

`BigDecimal`

###### chop(n)

```ts
chop(n): number | BigDecimal
```

####### n

`number` \| `BigDecimal`

</MemberCard>

<MemberCard>

##### ComputeEngine.array() {#array-1}

```ts
array(storage, cellType?): Expression & ArrayInterface
```

**`Experimental`**

A new mutable array that adopts the typed array `storage` as its cells,
with no pass over the cells and no copy: `ce.array(s).cells === s`.

Without `cellType`, the cell type is the full range of the storage kind:
`integer<0..255>` for a `Uint8Array`, `integer<-128..127>` for an
`Int8Array`, `integer<0..65535>` for a `Uint16Array`,
`integer<-32768..32767>` for an `Int16Array`, `integer<0..4294967295>`
for a `Uint32Array`, `integer<-2147483648..2147483647>` for an
`Int32Array` and `real` for a `Float64Array`.

A `cellType` must select the storage kind of `storage`. A tuple of four
bytes (`type Pixel = tuple<r: Byte, g: Byte, b: Byte, a: Byte>`) takes a
`Uint8Array` with four bytes for each cell, and the count is
`storage.length / 4`. The bytes of an `ImageData` are shared with:

```ts
const image = ce.array(new Uint8Array(data.data.buffer), 'Pixel');
```

The cells are not checked: each must hold a value of the cell type (see
`ArrayInterface`). `ce.arrayAllocation` and `ce.arrayCreated` are not
called.

Throws a `TypeError` for a value that is not a typed array, for a typed
array of a kind that has no cell type (`Float32Array`, `BigInt64Array`,
`BigUint64Array`, `Uint8ClampedArray`), for a view of a
`SharedArrayBuffer` or of a resizable `ArrayBuffer`, for a `cellType`
with expression cells or of
another storage kind, and for a tuple cell type with a length that is
not a multiple of 4.

####### storage

  \| `Uint8Array`\<`ArrayBufferLike`\>
  \| `Int8Array`\<`ArrayBufferLike`\>
  \| `Uint16Array`\<`ArrayBufferLike`\>
  \| `Int16Array`\<`ArrayBufferLike`\>
  \| `Uint32Array`\<`ArrayBufferLike`\>
  \| `Int32Array`\<`ArrayBufferLike`\>
  \| `Float64Array`\<`ArrayBufferLike`\>

####### cellType?

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

</MemberCard>

<MemberCard>

##### ComputeEngine.expr() {#expr-3}

```ts
expr(expr, options?): Expression
```

####### expr

  \| [`NumericValue`](#abstract-numericvalue)
  \| [`ExpressionInput`](#expressioninput)

####### options?

####### form?

[`FormOption`](#formoption)

####### scope?

`Scope`

</MemberCard>

<MemberCard>

##### ComputeEngine.~~box()~~ {#box-1}

```ts
box(expr, options?): Expression
```

####### expr

  \| [`NumericValue`](#abstract-numericvalue)
  \| [`ExpressionInput`](#expressioninput)

####### options?

####### form?

[`FormOption`](#formoption)

####### scope?

`Scope`

###### Deprecated

Use `expr()` instead.

</MemberCard>

<MemberCard>

##### ComputeEngine.rebind() {#rebind-1}

```ts
rebind(expr, options?): Expression
```

Rebuild `expr` as if `ce.expr(expr.json, { form, scope })` had been
called — every symbol resolves afresh in `scope` (or the current scope)
— without serializing `expr` to MathJSON.

`ce.expr(expr, { scope })` on an already-boxed expression keeps the
bindings the expression was boxed with; it never re-resolves a symbol.
This is the operation that does. Use it when an expression built under
one set of declarations must be read under another: a body boxed in a
shadow scope, a row re-classified after a declaration changed.

For the canonical and partial forms the MathJSON is built as a DAG — one
array per DISTINCT function node, shared by every parent that reads it
(a leaf contributes its own constant-size MathJSON) — where
`expr.json` writes a tree, one copy of a shared node per path. That
MathJSON is then boxed by the ordinary route, so the result matches
`ce.expr(expr.json, …)` by construction, including for an expression
that already holds an `Error` node. Canonical boxing still visits every
path, as it does for any MathJSON. The raw and structural forms
canonicalize nothing, so each distinct node is rebuilt once and a shared
sub-expression stays shared in the result as well.

- `form`: `'canonical'` (default), `'structural'`, `'raw'`, or a
  partial form such as `['Flatten', 'Order']`.
- `scope`: the lexical scope the rebuild resolves and declares in.

Verbatim LaTeX and source positions are dropped, as the MathJSON route
drops them. A mutable object is rebuilt as its record snapshot, as that
route boxes it.

To give a name a value for one evaluation, or to hide its value, use
`withValues()`, not a declaration in a pushed scope followed by
`rebind()`: a stored function that the expression calls reads the names
of the scope it was defined in, which a pushed scope does not change.

####### expr

[`Expression`](#expression-5)

####### options?

####### form?

[`FormOption`](#formoption)

####### scope?

`Scope`

</MemberCard>

<MemberCard>

##### ComputeEngine.parse() {#parse-2}

###### parse(latex, options)

```ts
parse(latex, options?): Expression
```

Parse a LaTeX string and return a boxed expression.

This is a convenience method equivalent to `ce.expr(parse(latex))`,
but uses the engine's symbol definitions for better parsing accuracy.

`options.scope` RECEIVES the parse's writes: the whole parse runs with
that scope as the current lexical scope, so name resolution (including
the parser's symbol oracle) walks `scope → parents`, and every
declaration and inference made while it runs lands rooted there. Boxing
itself declares no name. Discarding the scope discards the writes. Use `ce.createScope()` to make one that can be read
back.

`options.speculative` leaves NO trace in the engine's type state: the
parse runs inside a transient scope (declarations and inferences land
there and are discarded with it), and every ambient symbol whose type is currently
inferred is shadowed in that scope with its current type — so a
narrowing use in `latex` refines the discarded shadow instead of
persistently narrowing the ambient symbol. Use it for derive-style
parses that only READ the result (its type, structure, or
serialization): the result's bindings refer to the discarded scope, so
do not retain, evaluate, or compare it against later expressions.
Mutually exclusive with `scope`.

####### latex

`string`

####### options?

`Partial`\<[`ParseLatexOptions`](#parselatexoptions)\> & \{
  `form`: [`FormOption`](#formoption);
  `scope`: `Scope`;
  `speculative`: `boolean`;
 \}

###### parse(latex, options)

```ts
parse(latex, options?): Expression | null
```

####### latex

`string` \| `null`

####### options?

`Partial`\<[`ParseLatexOptions`](#parselatexoptions)\> & \{
  `form`: [`FormOption`](#formoption);
  `scope`: `Scope`;
  `speculative`: `boolean`;
 \}

</MemberCard>

<MemberCard>

##### ComputeEngine.appliedNonFunctions() {#appliednonfunctions-1}

```ts
appliedNonFunctions(latex): string[]
```

The symbols that appear in function-application syntax `f(…)` in `latex`
but are not defined as functions in the current scope (so they parse as
implicit multiplication or are left unresolved). Scope-aware and
side-effect-free. Intended to flag calls to undefined functions in tools
such as notebooks; intersect with [Expression.freeVariables](#freevariables)
to drop deliberate multiplication of defined values.

Only parenthesized-group application is detected: a symbol juxtaposed
with a matrix environment (`\mathrm{Eigenvalues}\begin{pmatrix}…`) is
not reported, since a matrix never reaches the symbol-with-delimiter
juxtaposition analysis.

####### latex

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.function() {#function-1}

```ts
function(name, ops, options?): Expression
```

####### name

`string`

####### ops

readonly [`ExpressionInput`](#expressioninput)[]

####### options?

####### metadata?

[`Metadata`](#metadata)

####### form?

[`FormOption`](#formoption)

####### scope?

`Scope`

</MemberCard>

<MemberCard>

##### ComputeEngine.number() {#number-2}

###### number(value, options)

```ts
number(value, options?): Expression
```

Create a complex number from its real part and its imaginary part, each
a JavaScript `number` or a `BigDecimal`.

When the engine works above machine precision (`ce.precision` greater
than 15), a `BigDecimal` part is kept at the precision it holds: a part
too small or too large for a double (`1e-800`, `1e800`) or with more
than 16 significant digits is not rounded to a double. This is the
lossless alternative to `ce.number(ce.complex(re, im))`: `ce.complex()`
returns a `Complex` object, whose parts are always doubles. At machine
precision, both parts are rounded to doubles: there
`{ re: ce.bignum('1e-800'), im: ce.bignum(2) }` gives `2i`.

When the imaginary part is zero (a `number` or a `BigDecimal`), the
result is a real number.

When both parts are integers, the result is the EXACT Gaussian integer,
as `ce.number(2)` is the exact `2`: a part is an integer when it is a
`number` that is a safe integer, or an integer-valued `BigDecimal` whose
exponent is at most `10^6` (also at machine precision, and also outside
the double range). When a part has a fraction, is a `number` past the
safe integers, or is a `BigDecimal` with a larger exponent (`1e2000000`),
the result is a float. A `Complex` given to `ce.number()` or `ce.box()`
does not follow this rule: it holds two doubles, so it is always a
float (`ce.number(new Complex(2, 3))` is the float `2.0 + 3.0i`).

```js
ce.precision = 30;
ce.number({ re: ce.bignum('1e-800'), im: ce.bignum(2) });
// ➔ a complex number with the real part 1e-800 and the imaginary part 2
ce.number({ re: 1, im: 0 });
// ➔ 1
ce.number({ re: 2, im: 3 }).isExact;
// ➔ true
ce.number({ re: 2.5, im: 3 }).isExact;
// ➔ false
```

####### value

####### re

`number` \| `BigDecimal`

####### im

`number` \| `BigDecimal`

####### options?

####### metadata?

[`Metadata`](#metadata)

####### canonical?

[`CanonicalOptions`](#canonicaloptions)

###### number(value, options)

```ts
number(value, options?): Expression
```

Create a number literal.

A JavaScript `number` that is a safe integer (`Number.isSafeInteger()`,
at most `2^53 − 1` in magnitude) is an exact integer. Any other
`number` is a float. Above machine precision a float holds its shortest
decimal, the digits `String(x)` prints, not the exact binary value of
the double: `ce.number(0.1)` is the decimal `0.1`, and
`ce.number(2 ** 60)` is `1152921504606847000`, not
`1152921504606846976`. At machine precision a float is the double.

An integer beyond `2^53 − 1` is exact when it is given as a `bigint` or
as a string of digits.

```js
ce.number(2 ** 60).isExact;
// ➔ false
ce.box(['Remainder', 2 ** 60, 7]).evaluate();
// ➔ -3 (the remainder of 1152921504606847000)
ce.function('Remainder', [ce.number(2n ** 60n), ce.number(7)]).evaluate();
// ➔ 1
ce.number('1152921504606846976').isExact;
// ➔ true
```

####### value

  \| `string`
  \| `number`
  \| `bigint`
  \| [`MathJsonNumberObject`](#mathjsonnumberobject)
  \| `BigDecimal`
  \| [`Rational`](#rational-1)
  \| [`NumericValue`](#abstract-numericvalue)
  \| `Complex`

####### options?

####### metadata?

[`Metadata`](#metadata)

####### canonical?

[`CanonicalOptions`](#canonicaloptions)

</MemberCard>

<MemberCard>

##### ComputeEngine.symbol() {#symbol-1}

```ts
symbol(sym, options?): Expression
```

####### sym

`string`

####### options?

####### canonical?

[`CanonicalOptions`](#canonicaloptions)

####### metadata?

[`Metadata`](#metadata)

####### autoDeclare?

`boolean`

</MemberCard>

<MemberCard>

##### ComputeEngine.string() {#string-2}

```ts
string(s, metadata?): Expression
```

####### s

`string`

####### metadata?

[`Metadata`](#metadata)

</MemberCard>

<MemberCard>

##### ComputeEngine.character() {#character-2}

```ts
character(s, metadata?): Expression
```

Create a boxed character — one user-perceived character.

`s` must be exactly one grapheme cluster after NFC normalization; use the
`CharacterFrom` operator when the content is not known to satisfy that, as
it reports a diagnostic instead.

####### s

`string`

####### metadata?

[`Metadata`](#metadata)

</MemberCard>

<MemberCard>

##### ComputeEngine.error() {#error-2}

```ts
error(message, where?): Expression
```

####### message

`string` \| `string`[]

####### where?

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.typeError() {#typeerror-1}

```ts
typeError(expectedType, actualType, where?): Expression
```

####### expectedType

[`Type`](#type-3)

####### actualType

  \| [`Type`](#type-3)
  \| [`BoxedType`](#boxedtype)
  \| `undefined`

####### where?

[`ExpressionInput`](#expressioninput)

</MemberCard>

<MemberCard>

##### ComputeEngine.hold() {#hold-1}

```ts
hold(expr): Expression
```

####### expr

[`ExpressionInput`](#expressioninput)

</MemberCard>

<MemberCard>

##### ComputeEngine.tuple() {#tuple-1}

###### tuple(elements)

```ts
tuple(...elements): Expression
```

####### elements

...readonly `number`[]

###### tuple(elements)

```ts
tuple(...elements): Expression
```

####### elements

...readonly [`Expression`](#expression-5)[]

</MemberCard>

<MemberCard>

##### ComputeEngine.list() {#list-1}

```ts
list(values): Expression
```

A `List` of numbers, built without boxing each element.

The elements are copied into a frozen array of machine numbers that the
list keeps as its store: `count`, `at`, `type`, `isSame` and `array`
answer from it, and the boxed operands are built only if `ops` is read.
The result is an ordinary canonical `List` in every other respect.

`values` may be a `number[]`, a `Float64Array` or any array-like of
numbers. Its `length` must be a non-negative safe integer and each
element a JS number; anything else throws a `TypeError`. `-0` is stored
as `+0`.

Use it to hand a large numeric list to the engine cheaply, and read it
back with `expr.array`.

####### values

`ArrayLike`\<`number`\>

</MemberCard>

<MemberCard>

##### ComputeEngine.type() {#type-11}

```ts
type(type): BoxedType
```

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

</MemberCard>

<MemberCard>

##### ComputeEngine.rules() {#rules-2}

```ts
rules(rules, options?): BoxedRuleSet
```

####### rules

`Rule` \| readonly Rule \| BoxedRule[] \| `BoxedRuleSet` \| `null` \| `undefined`

####### options?

####### canonical?

`boolean`

####### purpose?

[`RulePurpose`](#rulepurpose)

Default purpose applied to any rule in the set that doesn't carry
 its own `purpose` tag (a per-rule tag takes precedence).

</MemberCard>

<MemberCard>

##### ComputeEngine.getRuleSet() {#getruleset-1}

```ts
getRuleSet(id?): BoxedRuleSet | undefined
```

####### id?

`"harmonization"` \| `"solve-univariate"` \| `"standard-simplification"`

</MemberCard>

<MemberCard>

##### ComputeEngine.pushScope() {#pushscope-1}

```ts
pushScope(scope?, name?): void
```

####### scope?

`Scope`

####### name?

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.popScope() {#popscope-1}

```ts
popScope(): void
```

</MemberCard>

<MemberCard>

##### ComputeEngine.createScope() {#createscope-1}

```ts
createScope(bindings?, parent?): InspectableScope
```

####### bindings?

`Record`\<`string`, 
  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`TaggedValueDefinition`](#taggedvaluedefinition)
  \| [`TaggedOperatorDefinition`](#taggedoperatordefinition)\>

####### parent?

`Scope`

</MemberCard>

<MemberCard>

##### ComputeEngine.lookupDefinition() {#lookupdefinition-2}

```ts
lookupDefinition(id): BoxedDefinition | undefined
```

####### id

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.assign() {#assign-1}

###### assign(ids)

```ts
assign(ids): IComputeEngine
```

####### ids

\{\}

###### assign(id, value)

```ts
assign(id, value): IComputeEngine
```

####### id

`string`

####### value

`AssignValue`

###### assign(arg1, arg2)

```ts
assign(arg1, arg2?): IComputeEngine
```

####### arg1

`string` \| \{\}

####### arg2?

`AssignValue`

</MemberCard>

<MemberCard>

##### ComputeEngine.withValues() {#withvalues-1}

```ts
withValues<T>(values, fn): T
```

Run `fn` with each symbol of `values` bound to the given value, and
put back the earlier value and type of each symbol when `fn` returns or
throws. `fn` must be synchronous.

• T

####### values

\{\}

####### fn

() => `T`

</MemberCard>

<MemberCard>

##### ComputeEngine.declareType() {#declaretype-1}

```ts
declareType(name, type, options?): void
```

####### name

`string`

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

####### options?

####### alias?

`boolean`

####### fromStatement?

`boolean`

####### mint?

`boolean`

Whether the declaration also declares a value-level constructor
of the same name (`point(1, 2)` for `type point = tuple<…>`). Default
`true`. A VALUE KIND uses `false`: its type is a nominal type defined
as exactly `value` (`ce.declareType('gf8', 'value', { mint: false })`),
and its values are made by the head that declares its arithmetic
(`GF8(3)`), so a second constructor with no arithmetic must not
exist. See the `arithmetic` field of `OperatorDefinition`.

####### typeParams?

[`TypeParamsOption`](#typeparamsoption)

</MemberCard>

<MemberCard>

##### ComputeEngine.declare() {#declare-1}

###### declare(symbols)

```ts
declare(symbols): IComputeEngine
```

####### symbols

\{\}

###### declare(id, type, scope)

```ts
declare(id, type, scope?): IComputeEngine
```

####### id

`string`

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)

####### scope?

  \| `Scope`
  \| [`DeclareOptions`](#declareoptions) & \{
  `extend`: `false`;
 \}

###### declare(id, patch, options)

```ts
declare(id, patch, options): IComputeEngine
```

####### id

`string`

####### patch

[`OperatorDefinitionPatch`](#operatordefinitionpatch)

####### options

[`DeclareOptions`](#declareoptions) & \{
  `extend`: `true`;
 \}

###### declare(id, def, scope)

```ts
declare(id, def, scope?): IComputeEngine
```

####### id

`string`

####### def

[`SymbolDefinitionInput`](#symboldefinitioninput)

####### scope?

  \| `Scope`
  \| [`DeclareOptions`](#declareoptions) & \{
  `extend`: `false`;
 \}

###### declare(arg1, arg2, arg3)

```ts
declare(arg1, arg2?, arg3?): IComputeEngine
```

####### arg1

`string` \| \{\}

####### arg2?

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| `Partial`\<`OnlyFirst`\<[`ValueDefinition`](#valuedefinition), [`BaseDefinition`](#basedefinition) & \{
  `holdUntil`: `"never"` \| `"evaluate"` \| `"N"`;
  `type`:   \| `string`
     \| [`RecordType`](#recordtype)
     \| [`AlgebraicType`](#algebraictype)
     \| [`NegationType`](#negationtype)
     \| [`CollectionType`](#collectiontype)
     \| [`ListType`](#listtype)
     \| [`SetType`](#settype)
     \| [`BroadcastableType`](#broadcastabletype)
     \| [`ObjectType`](#objecttype)
     \| [`ArrayType`](#arraytype)
     \| [`DictionaryType`](#dictionarytype)
     \| [`TupleType`](#tupletype)
     \| [`SymbolType`](#symboltype)
     \| [`ExpressionType`](#expressiontype)
     \| [`NumericType`](#numerictype)
     \| [`FunctionSignature`](#functionsignature)
     \| [`ValueType`](#valuetype)
     \| [`TypeVariable`](#typevariable)
     \| [`TypeReference`](#typereference)
     \| [`BoxedType`](#boxedtype);
  `inferred`: `boolean`;
  `effectsDeclared`: `boolean`;
  `value`:   \| [`ExpressionInput`](#expressioninput)
     \| ((`ce`) => [`Expression`](#expression-5) \| `null`);
  `macro`: [`MathJsonExpression`](#mathjsonexpression);
  `eq`: (`a`) => `boolean` \| `undefined`;
  `neq`: (`a`) => `boolean` \| `undefined`;
  `cmp`: (`a`) => `"<"` \| `">"` \| `"="` \| `undefined`;
  `collection`: [`CollectionHandlers`](#collectionhandlers);
  `subscriptEvaluate`: (`subscript`, `options`) => [`Expression`](#expression-5) \| `undefined`;
 \} & `Partial`\<[`BaseDefinition`](#basedefinition)\> & `Partial`\<[`OperatorDefinitionFlags`](#operatordefinitionflags)\> & \{
  `type`: [`OperatorTypeHandlerOnTypes`](#operatortypehandlerontypes);
  `signature`:   \| `string`
     \| [`RecordType`](#recordtype)
     \| [`AlgebraicType`](#algebraictype)
     \| [`NegationType`](#negationtype)
     \| [`CollectionType`](#collectiontype)
     \| [`ListType`](#listtype)
     \| [`SetType`](#settype)
     \| [`BroadcastableType`](#broadcastabletype)
     \| [`ObjectType`](#objecttype)
     \| [`ArrayType`](#arraytype)
     \| [`DictionaryType`](#dictionarytype)
     \| [`TupleType`](#tupletype)
     \| [`SymbolType`](#symboltype)
     \| [`ExpressionType`](#expressiontype)
     \| [`NumericType`](#numerictype)
     \| [`FunctionSignature`](#functionsignature)
     \| [`ValueType`](#valuetype)
     \| [`TypeVariable`](#typevariable)
     \| [`TypeReference`](#typereference)
     \| [`BoxedType`](#boxedtype);
  `parameters`:   \| `Readonly`\<`Record`\<`string`, [`ParameterDocumentation`](#parameterdocumentation)\>\>
     \| readonly [`ParameterDocumentation`](#parameterdocumentation)[];
  `inferredSignature`: `boolean`;
  `sgn`: (`ops`, `options`) => [`Sign`](#sign) \| `undefined`;
  `isPositive`: `boolean`;
  `isNonNegative`: `boolean`;
  `isNegative`: `boolean`;
  `isNonPositive`: `boolean`;
  `even`: (`ops`, `options`) => `boolean` \| `undefined`;
  `complexity`: `number`;
  `canonical`: (`ops`, `options`) => [`Expression`](#expression-5) \| `null`;
  `evaluate`:   \| [`Expression`](#expression-5)
     \| ((`ops`, `options`) => [`Expression`](#expression-5) \| `undefined`);
  `evaluateAsync`: (`ops`, `options`) => `Promise`\<[`Expression`](#expression-5) \| `undefined`\>;
  `evaluateMod`: [`EvaluateModHandler`](#evaluatemodhandler);
  `evalDimension`: (`args`, `options`) => [`Expression`](#expression-5);
  `derivative`: [`OperatorDerivative`](#operatorderivative);
  `compile`: [`OperatorCompileHandler`](#operatorcompilehandler);
  `eq`: (`a`, `b`, `prover?`) => `boolean` \| `undefined`;
  `neq`: (`a`, `b`) => `boolean` \| `undefined`;
  `collection`: [`CollectionHandlers`](#collectionhandlers);
  `arithmetic`: [`ArithmeticDefinition`](#arithmeticdefinition);
  `canEnumerate`: (`expr`) => `boolean` \| `undefined`;
  `elementCount`: (`expr`) => `number` \| `undefined`;
  `elementAt`: (`expr`, `index`) => [`Expression`](#expression-5) \| `undefined`;
  `inferOperandTypes`: (`ops`, `requirement`) => 
     \| readonly (
     \| [`Type`](#type-3)
     \| \{
     `replace`: ...;
    \}
     \| `undefined`)[]
     \| `undefined`;
 \}\>\>
  \| `Partial`\<`OnlyFirst`\<[`OperatorDefinition`](#operatordefinition), [`BaseDefinition`](#basedefinition) & \{
  `holdUntil`: `"never"` \| `"evaluate"` \| `"N"`;
  `type`:   \| `string`
     \| [`RecordType`](#recordtype)
     \| [`AlgebraicType`](#algebraictype)
     \| [`NegationType`](#negationtype)
     \| [`CollectionType`](#collectiontype)
     \| [`ListType`](#listtype)
     \| [`SetType`](#settype)
     \| [`BroadcastableType`](#broadcastabletype)
     \| [`ObjectType`](#objecttype)
     \| [`ArrayType`](#arraytype)
     \| [`DictionaryType`](#dictionarytype)
     \| [`TupleType`](#tupletype)
     \| [`SymbolType`](#symboltype)
     \| [`ExpressionType`](#expressiontype)
     \| [`NumericType`](#numerictype)
     \| [`FunctionSignature`](#functionsignature)
     \| [`ValueType`](#valuetype)
     \| [`TypeVariable`](#typevariable)
     \| [`TypeReference`](#typereference)
     \| [`BoxedType`](#boxedtype);
  `inferred`: `boolean`;
  `effectsDeclared`: `boolean`;
  `value`:   \| [`ExpressionInput`](#expressioninput)
     \| ((`ce`) => [`Expression`](#expression-5) \| `null`);
  `macro`: [`MathJsonExpression`](#mathjsonexpression);
  `eq`: (`a`) => `boolean` \| `undefined`;
  `neq`: (`a`) => `boolean` \| `undefined`;
  `cmp`: (`a`) => `"<"` \| `">"` \| `"="` \| `undefined`;
  `collection`: [`CollectionHandlers`](#collectionhandlers);
  `subscriptEvaluate`: (`subscript`, `options`) => [`Expression`](#expression-5) \| `undefined`;
 \} & `Partial`\<[`BaseDefinition`](#basedefinition)\> & `Partial`\<[`OperatorDefinitionFlags`](#operatordefinitionflags)\> & \{
  `type`: [`OperatorTypeHandlerOnTypes`](#operatortypehandlerontypes);
  `signature`:   \| `string`
     \| [`RecordType`](#recordtype)
     \| [`AlgebraicType`](#algebraictype)
     \| [`NegationType`](#negationtype)
     \| [`CollectionType`](#collectiontype)
     \| [`ListType`](#listtype)
     \| [`SetType`](#settype)
     \| [`BroadcastableType`](#broadcastabletype)
     \| [`ObjectType`](#objecttype)
     \| [`ArrayType`](#arraytype)
     \| [`DictionaryType`](#dictionarytype)
     \| [`TupleType`](#tupletype)
     \| [`SymbolType`](#symboltype)
     \| [`ExpressionType`](#expressiontype)
     \| [`NumericType`](#numerictype)
     \| [`FunctionSignature`](#functionsignature)
     \| [`ValueType`](#valuetype)
     \| [`TypeVariable`](#typevariable)
     \| [`TypeReference`](#typereference)
     \| [`BoxedType`](#boxedtype);
  `parameters`:   \| `Readonly`\<`Record`\<`string`, [`ParameterDocumentation`](#parameterdocumentation)\>\>
     \| readonly [`ParameterDocumentation`](#parameterdocumentation)[];
  `inferredSignature`: `boolean`;
  `sgn`: (`ops`, `options`) => [`Sign`](#sign) \| `undefined`;
  `isPositive`: `boolean`;
  `isNonNegative`: `boolean`;
  `isNegative`: `boolean`;
  `isNonPositive`: `boolean`;
  `even`: (`ops`, `options`) => `boolean` \| `undefined`;
  `complexity`: `number`;
  `canonical`: (`ops`, `options`) => [`Expression`](#expression-5) \| `null`;
  `evaluate`:   \| [`Expression`](#expression-5)
     \| ((`ops`, `options`) => [`Expression`](#expression-5) \| `undefined`);
  `evaluateAsync`: (`ops`, `options`) => `Promise`\<[`Expression`](#expression-5) \| `undefined`\>;
  `evaluateMod`: [`EvaluateModHandler`](#evaluatemodhandler);
  `evalDimension`: (`args`, `options`) => [`Expression`](#expression-5);
  `derivative`: [`OperatorDerivative`](#operatorderivative);
  `compile`: [`OperatorCompileHandler`](#operatorcompilehandler);
  `eq`: (`a`, `b`, `prover?`) => `boolean` \| `undefined`;
  `neq`: (`a`, `b`) => `boolean` \| `undefined`;
  `collection`: [`CollectionHandlers`](#collectionhandlers);
  `arithmetic`: [`ArithmeticDefinition`](#arithmeticdefinition);
  `canEnumerate`: (`expr`) => `boolean` \| `undefined`;
  `elementCount`: (`expr`) => `number` \| `undefined`;
  `elementAt`: (`expr`, `index`) => [`Expression`](#expression-5) \| `undefined`;
  `inferOperandTypes`: (`ops`, `requirement`) => 
     \| readonly (
     \| [`Type`](#type-3)
     \| \{
     `replace`: ...;
    \}
     \| `undefined`)[]
     \| `undefined`;
 \}\>\>
  \| [`BoxedOperatorDefinition`](#boxedoperatordefinition)
  \| [`OperatorDefinitionPatch`](#operatordefinitionpatch)

####### arg3?

`Scope` \| [`DeclareOptions`](#declareoptions)

</MemberCard>

<MemberCard>

##### ComputeEngine.loadLibrary() {#loadlibrary-1}

```ts
loadLibrary(library): IComputeEngine
```

Load a library on an engine that is already constructed. Its
definitions are declared in the global scope, as with `ce.declare()`,
and its name is recorded (see `libraryOf()`). Each library in its
`requires` list must already be loaded.

####### library

[`LibraryDefinition`](#librarydefinition)

</MemberCard>

<MemberCard>

##### ComputeEngine.libraryOf() {#libraryof-1}

```ts
libraryOf(name): string | undefined
```

The name of the library whose definition `name` resolves to in the
current scope (`'trigonometry'` for `Sin`), or `undefined` for a name
that no library defines or that a declaration shadows.

####### name

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.assume() {#assume-1}

```ts
assume(predicate): AssumeResult
```

####### predicate

`string` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### ComputeEngine.infer() {#infer-1}

```ts
infer(exprs): InferResult
```

**`Experimental`**

Declare the names that `exprs` use, with the types that their uses
require.

Each name is declared, marked as inferred, in its home scope: the scope
that a declaration of the name would go in when the expression that uses
it was boxed. When the home scope already holds an inferred definition
of the name, that definition is narrowed instead. The type is the meet of
the types that the uses in `exprs` require, met with the type of that
inferred definition. The order of `exprs` does not change the result.

A name is not changed, and is reported in `skipped`, when the uses
require types that have no common subtype (`x + 1` and `x(3)`), when
they require no type, when the home scope holds a definition of the name
that is not inferred, and when the home scope is not the current scope
or one of its ancestors. Each expression then keeps the type that its
own uses require.

A library name used as a value (`N` in `N + 1`) is declared as a
variable, which shadows the library definition in the home scope. A
call head (`f` in `f(x)`) is declared with a function type.

####### exprs

readonly [`Expression`](#expression-5)[]

</MemberCard>

<MemberCard>

##### ComputeEngine.declareSequence() {#declaresequence-1}

```ts
declareSequence(name, def): IComputeEngine
```

Declare a sequence with a recurrence relation.

####### name

`string`

####### def

[`SequenceDefinition`](#sequencedefinition)

###### Example

```typescript
// Fibonacci sequence
ce.declareSequence('F', {
  base: { 0: 0, 1: 1 },
  recurrence: 'F_{n-1} + F_{n-2}',
});
ce.parse('F_{10}').evaluate();  // → 55
```

</MemberCard>

<MemberCard>

##### ComputeEngine.getSequenceStatus() {#getsequencestatus-1}

```ts
getSequenceStatus(name): SequenceStatus
```

Get the status of a sequence definition.

####### name

`string`

###### Example

```typescript
ce.parse('F_0 := 0').evaluate();
ce.getSequenceStatus('F');
// → { status: 'pending', hasBase: true, hasRecurrence: false, baseIndices: [0] }
```

</MemberCard>

<MemberCard>

##### ComputeEngine.getSequence() {#getsequence-1}

```ts
getSequence(name): SequenceInfo | undefined
```

Get information about a defined sequence.
Returns `undefined` if the symbol is not a sequence.

####### name

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.listSequences() {#listsequences-1}

```ts
listSequences(): string[]
```

List all defined sequences.
Returns an array of sequence names.

A name is listed when the definition it has in the current scope is a
sequence, as for `isSequence()`.

</MemberCard>

<MemberCard>

##### ComputeEngine.isSequence() {#issequence-1}

```ts
isSequence(name): boolean
```

Check if a symbol is a defined sequence.

The answer is for the definition that the name has in the current
scope. A sequence declared in an enclosing scope is a sequence. A
sequence is no longer one after the scope that declared it is popped,
or after `undeclare()`.

####### name

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.clearSequenceCache() {#clearsequencecache-1}

```ts
clearSequenceCache(name?): void
```

Clear the memoization cache for a sequence.
If no name is provided, clears caches for all sequences.

####### name?

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.getSequenceCache() {#getsequencecache-1}

```ts
getSequenceCache(name): 
  | Map<string | number, Expression>
  | undefined
```

Get the memoization cache for a sequence.
Returns a Map of index → value, or `undefined` if not a sequence or memoization is disabled.

For single-index sequences, keys are numbers.
For multi-index sequences, keys are comma-separated strings (e.g., '5,2').

####### name

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.getSequenceTerms() {#getsequenceterms-1}

```ts
getSequenceTerms(
   name, 
   start, 
   end, 
   step?): Expression[] | undefined
```

Generate a list of sequence terms from start to end (inclusive).

####### name

`string`

The sequence name

####### start

`number`

Starting index (inclusive)

####### end

`number`

Ending index (inclusive)

####### step?

`number`

Step size (default: 1)

###### Example

```typescript
ce.declareSequence('F', { base: { 0: 0, 1: 1 }, recurrence: 'F_{n-1} + F_{n-2}' });
ce.getSequenceTerms('F', 0, 10);
// → [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
```

</MemberCard>

<MemberCard>

##### ComputeEngine.lookupOEIS() {#lookupoeis-1}

```ts
lookupOEIS(terms, options?): Promise<OEISSequenceInfo[]>
```

Look up sequences in OEIS by their terms.

####### terms

(`number` \| [`Expression`](#expression-5))[]

Array of sequence terms to search for

####### options?

[`OEISOptions`](#oeisoptions)

Optional configuration (timeout, maxResults)

###### Example

```typescript
const results = await ce.lookupOEIS([0, 1, 1, 2, 3, 5, 8, 13]);
// → [{ id: 'A000045', name: 'Fibonacci numbers', ... }]
```

</MemberCard>

<MemberCard>

##### ComputeEngine.checkSequenceOEIS() {#checksequenceoeis-1}

```ts
checkSequenceOEIS(name, count?, options?): Promise<{
  matches: OEISSequenceInfo[];
  terms: number[];
}>
```

Check if a defined sequence matches an OEIS sequence.

####### name

`string`

Name of the defined sequence

####### count?

`number`

Number of terms to check (default: 10)

####### options?

[`OEISOptions`](#oeisoptions)

Optional configuration

###### Example

```typescript
ce.declareSequence('F', { base: { 0: 0, 1: 1 }, recurrence: 'F_{n-1} + F_{n-2}' });
const result = await ce.checkSequenceOEIS('F', 10);
// → { matches: [{ id: 'A000045', name: 'Fibonacci numbers', ... }], terms: [0, 1, 1, ...] }
```

</MemberCard>

<MemberCard>

##### ComputeEngine.interpret() {#interpret-1}

```ts
interpret(expr, options?): Promise<InterpretResult>
```

Interpret a notational expression, then propose OEIS-attributed closed
forms for it (the async v4 of the `Interpret` ladder).

`result.expression` is exactly what the synchronous `Interpret` head
returns (a `Sum`/`Product`, or the input unchanged); `result.candidates`
are OEIS-attributed closed forms, each verified to reproduce every
extracted sample exactly. This is the only interpretation path that
performs a network lookup. Too few samples, being offline, a timeout, or an
empty result all yield an empty candidate list rather than a rejection.

####### expr

[`Expression`](#expression-5)

The (typically inert, continuation-bearing) expression

####### options?

[`OEISOptions`](#oeisoptions)

OEIS request options (timeout, maxResults)

###### Example

```typescript
const { expression, candidates } = await ce.interpret(
  ce.parse('1 + 3 + 6 + 10 + \\cdots + n')
);
```

</MemberCard>

<MemberCard>

##### ComputeEngine.forget() {#forget-1}

```ts
forget(symbol?): void
```

####### symbol?

`string` \| `string`[]

</MemberCard>

<MemberCard>

##### ComputeEngine.undeclare() {#undeclare-1}

```ts
undeclare(names): void
```

Remove the binding of one or more names from the current scope.

The binding goes whatever it holds: a value, a function given with
`ce.assign()` or `ce.declare()`, or a function defined by one or more
clauses (`f(x) := …`, `DefineFunction`). This is different from
`forget()`, which removes assumptions and keeps the declaration.

After the call, the name is not declared in the current scope:

- When an enclosing scope declares the name, that declaration applies
  again. `undeclare()` does not change an enclosing scope.
- Otherwise, the name is a free symbol: `f(2)` stays unevaluated as
  `["f", 2]`, and `x + 1` stays symbolic.
- A later `ce.declare()`, `ce.assign()`, `f(x) := …` or `DefineFunction`
  of the name is a new declaration, and is accepted.

An expression boxed before the call does not use the removed binding
either. A symbol reads the value that the scope chain holds when the
expression is evaluated. A call such as `f(2)` boxed before the call
evaluates to `["f", 2]`, and after a new definition of `f` in the same
scope it uses the new definition, as for a function given again with
`ce.assign()`.

Assumptions about the name are not removed: an assumption applies to
the name, and so to a new declaration of it. Use `forget()` to remove
them.

####### names

`string` \| readonly `string`[]

###### Throws

if a name is not declared in the current scope. A name declared
only in an enclosing scope is not declared in the current scope. To
remove a name only when it is declared, test
`ce.context.lexicalScope.bindings.has(name)` first.

###### Throws

if a name is defined by a library: a standard library, a library
given to the constructor, or a library loaded with `ce.loadLibrary()`.
Also throws for any name of the system scope, which holds the standard
library.

###### Throws

if a name is the variable of an operator such as `Sum`, or a
parameter of a function, while that expression is evaluated.

When one name of a list is refused, no binding is removed.

```ts
ce.pushScope();
ce.parse('f(n) := n + 1').evaluate();
ce.parse('f(2)').evaluate();   // 3
ce.undeclare('f');
ce.parse('f(2)').evaluate();   // f(2)
```

</MemberCard>

<MemberCard>

##### ComputeEngine.ask() {#ask-1}

```ts
ask(pattern): BoxedSubstitution[]
```

####### pattern

[`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### ComputeEngine.verify() {#verify-1}

```ts
verify(query): boolean | undefined
```

####### query

`string` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### ComputeEngine.operatorInfo() {#operatorinfo-2}

```ts
operatorInfo(head): OperatorInfo | undefined
```

Introspect a registered operator head.

Returns `undefined` if no definition is registered in this engine.
Otherwise returns `{ kind, signature? }` where `kind` is `'function'`
when the operator has an `evaluate` or `collection` handler, and
`'opaque'` when it is declared as a typed-but-opaque node (e.g.,
`Triangle`, `Angle`).

Use this to classify heads encountered in parsed MathJSON without
maintaining a parallel list of "known" operators.

####### head

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.normalizeIdentifier() {#normalizeidentifier-1}

```ts
normalizeIdentifier(latex): string
```

Convert a LaTeX identifier string to its canonical MathJSON name without
declaring the symbol in the engine scope.

Examples:
- `'R_{3}'` → `'R_3'`
- `'\\theta_x'` → `'theta_x'`
- `'\\alpha'` → `'alpha'`
- `'1 + 2'` → `''` (not an identifier)

Use this instead of `ce.parse(latex).symbol` when you need the canonical
name without the side-effect of auto-declaring the symbol.

####### latex

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.symbolInfo() {#symbolinfo-2}

```ts
symbolInfo(name): SymbolInfo | undefined
```

Return introspection metadata for a symbol (value definition) in the
current scope chain.

- `kind: 'constant'` when the symbol is a CE-registered constant
  (e.g. `Pi`, `True`, `ExponentialE`).
- `kind: 'variable'` for declared but non-constant value symbols
  (e.g. after `ce.declare('a', 'real')`).

Returns `undefined` for unknown names and for names that resolve to
operator/function definitions (use `operatorInfo()` for those — the
two methods are non-overlapping).

####### name

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.searchDefinitions() {#searchdefinitions-1}

```ts
searchDefinitions(query, options?): DefinitionSearchResult[]
```

Reverse library search: map plain-text concept keywords to a ranked list
of matching identifiers in the current scope chain (standard library plus
any user declarations).

The query is a string (tokenized on whitespace) or an array of strings;
tokens are OR-ed — a definition matches when **any** token matches — and
definitions matching more tokens, or matching them more exactly, rank
higher.

Every returned `id` resolves via `ce.lookupDefinition(id)`; chain that
call for full detail.

####### query

`string` \| `string`[]

####### options?

####### limit?

`number`

</MemberCard>

<MemberCard>

##### ComputeEngine.suggestOperatorName() {#suggestoperatorname-1}

```ts
suggestOperatorName(name): string | undefined
```

Given a `name` that is **not** a known operator, return the closest known
operator name — a "did you mean" suggestion — or `undefined` when nothing
is close enough. Powers the Epsil `unknown-function` diagnostic.

Matching is conservative and applied in priority order (first match wins):
case-insensitive exact match, singular/plural, Damerau–Levenshtein
distance (≤ 2 for names of length ≥ 6, ≤ 1 for length 5, never for
shorter names), then a prefix match against exactly one operator. Ties
prefer the candidate sharing the longest prefix with the query.

```ts
ce.suggestOperatorName('Quartile'); // → 'Quartiles'
ce.suggestOperatorName('foo');      // → undefined
```

####### name

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.temporaryName() {#temporaryname-1}

```ts
temporaryName(hint, ...avoid): string
```

Return a name for a temporary symbol: `<hint>_tmp<n>`, with `n` the
smallest integer from 1 such that the name
- has no definition that `ce.lookupDefinition()` finds from the current
  scope, and
- is not a name of `avoid`, and does not occur in an expression of
  `avoid`, as a symbol (free or bound) or as the operator of a call.

Each item of `avoid` is a boxed expression, a string (one name, not text
to search) or a set of names. An array throws: an array of strings is
also a MathJSON call, so box it or pass the set of its names. An
expression is walked as it is written, each shared subtree once; the
walk does not enter the values or the bodies of the names it reads.

Pass in `avoid` every expression that the name will be put in or
combined with, the bodies and stored values that the computation reads,
and the names returned by earlier calls that are not declared yet: two
calls in a row with the same hint return the same name otherwise. A name
that an expression uses with no definition is not seen by the lookup.

The hint is cleaned: the `_` at its start and at its end are removed and
each `__` becomes `_`; `tmp` is used if nothing is left. A hint that is
not a valid symbol name, or for which `<hint>_tmp1` is not one (an
emoji), throws.

The function keeps no state and declares nothing: the same call in the
same state returns the same name. The caller declares the name if it
needs a definition, and the definition ends with its scope.

A name that ends with `_tmp` and a positive integer is reserved for this
function. The engine does not enforce it. A host can remove
`/_tmp[1-9]\d*$/` from the name to get the hint.

```ts
ce.temporaryName('t');                                // → 't_tmp1'
ce.temporaryName('t', ce.box(['Add', 't_tmp1', 'x'])); // → 't_tmp2'
ce.temporaryName('s', new Set(['s_tmp1']));           // → 's_tmp2'
ce.temporaryName('_x');                               // → 'x_tmp1'
```

####### hint

`string`

####### avoid

...(`string` \| `ReadonlySet`\<`string`\> \| [`Expression`](#expression-5))[]

</MemberCard>

<MemberCard>

##### ComputeEngine.functionProperties() {#functionproperties-2}

```ts
functionProperties(name): FunctionProperties | undefined
```

Return the known analytic properties of an operator — poles, zeros, branch
points/cuts, residues, holomorphic/meromorphic domains — drawn from the
Fungrim-derived metadata store, or `undefined` if none are recorded.

```ts
ce.functionProperties('Gamma')?.poles?.toString(); // 'NonPositiveIntegers'
```

The set-valued accessors (`poles`, `zeros`, ...) return a boxed set for the
unconditional record of that kind; parametric / conditional records (e.g.
residues that depend on parameters) are available via `entries`.

####### name

`string`

</MemberCard>

<MemberCard>

##### ComputeEngine.contourIntegrate() {#contourintegrate-1}

```ts
contourIntegrate(integrand, variable, contour): ContourIntegralResult
```

Integrate over a circle, simple polygon, or the entire real line by the
residue theorem. Real-line contours also accept an explicit principal value.
Returns pole classifications, residues, their sum, and the integral.
Unsupported or undecidable inputs have no value; boundary poles have
status `pole-on-contour`. See [ContourInput](#contourinput) for contour forms.

####### integrand

[`ExpressionInput`](#expressioninput)

####### variable

`string`

####### contour

[`ContourInput`](#contourinput)

</MemberCard>

<MemberCard>

##### ComputeEngine.toJSON() {#tojson-3}

```ts
toJSON(): string
```

Debug representation, e.g. for `JSON.stringify()`.

</MemberCard>

## Boxed Expression

<MemberCard>

### SimplifyOptions {#simplifyoptions}

```ts
type SimplifyOptions = {
  rules: null | Rule | ReadonlyArray<BoxedRule | Rule> | BoxedRuleSet;
  costFunction: (expr) => number;
  strategy: "default" | "fu" | "trig";
};
```

Options for `Expression.simplify()`

</MemberCard>

<MemberCard>

### ExplainOptions {#explainoptions}

```ts
type ExplainOptions = SimplifyOptions & {
  verbosity: ExplainVerbosity;
  variable: string | string[];
  order: number;
};
```

Options for `Expression.explain()`

In addition to the `SimplifyOptions` (honored when explaining a
`'simplify'` operation, so that `explain('simplify', options).result`
matches `simplify(options)`):

- `verbosity`: `'default'` returns the curated step chain (bookkeeping
  steps filtered out); `'all'` returns the raw, uncurated chain.
- `variable`: the unknown, for the `'solve'` and `'D'` operations. For a
  system of equations (`explain('solve')` on a `List`/`And`), pass the
  unknowns as an array, in order.
- `order`: for the `'D'` operation only, the order of the derivative to
  explain (the n-th derivative with respect to `variable`). Defaults to `1`.
  Ignored when the receiver is already a `D(…)` expression (which encodes
  its own differentiation sequence).

</MemberCard>

<MemberCard>

### EvaluateOptions {#evaluateoptions}

```ts
type EvaluateOptions = KernelEvaluateOptions;
```

Options for evaluating boxed expressions.

This is the compute-engine-specialized form of the generic kernel type.

</MemberCard>

<MemberCard>

### IntervalBounds {#intervalbounds}

```ts
type IntervalBounds = {
  lower: Expression;
  lowerStrict: boolean;
  upper: Expression;
  upperStrict: boolean;
};
```

Lower and upper bounds for a symbol extracted from a domain restriction.

`lowerStrict`/`upperStrict` are `true` for strict (`<`, `>`) bounds and
`false` (or `undefined`) for non-strict (`≤`, `≥`) bounds.

</MemberCard>

<MemberCard>

### StaticShape {#staticshape}

```ts
type StaticShape = {
  indexed: boolean;
  count: number | bigint | undefined;
  elementType: Type | undefined;
};
```

The collection shape that an expression promises before it is evaluated.
See `Expression.staticShape`.

</MemberCard>

### NumberLiteralInterface {#numberliteralinterface}

Narrowed interface for number literal expressions.

Obtained via `isNumber()`.

<MemberCard>

##### NumberLiteralInterface.numericValue {#numericvalue-1}

```ts
readonly numericValue: number | NumericValue;
```

</MemberCard>

<MemberCard>

##### NumberLiteralInterface.isExact {#isexact-2}

```ts
readonly isExact: boolean;
```

</MemberCard>

<MemberCard>

##### NumberLiteralInterface.isComplex {#iscomplex-1}

```ts
readonly isComplex: boolean;
```

True if the imaginary part of this number is not zero.

Unlike a test of `im !== 0`, this is `true` for an imaginary part too
small or too large for a double (the exact `10^{-800}·i`), because it is
read from the numeric value itself, not from its double projection
`im`.

</MemberCard>

<MemberCard>

##### NumberLiteralInterface.isNumberLiteral {#isnumberliteral}

```ts
readonly isNumberLiteral: true;
```

</MemberCard>

### SymbolInterface {#symbolinterface}

Narrowed interface for symbol expressions.

Obtained via `isSymbol()`.

<MemberCard>

##### SymbolInterface.symbol {#symbol-2}

```ts
readonly symbol: string;
```

</MemberCard>

### FunctionInterface {#functioninterface}

Narrowed interface for function expressions.

Obtained via `isFunction()`.

<MemberCard>

##### FunctionInterface.isFunctionExpression {#isfunctionexpression}

```ts
readonly isFunctionExpression: true;
```

</MemberCard>

<MemberCard>

##### FunctionInterface.ops {#ops-1}

```ts
readonly ops: readonly Expression[];
```

</MemberCard>

<MemberCard>

##### FunctionInterface.nops {#nops}

```ts
readonly nops: number;
```

</MemberCard>

<MemberCard>

##### FunctionInterface.\_numericStore {#_numericstore}

```ts
readonly _numericStore: readonly number[] | undefined;
```

Internal. The numeric store of a `List` built by `ce.list()`: its
elements as frozen machine numbers, from which the operands are boxed on
the first read of `ops`. `undefined` for every other function
expression. A walker that only looks for symbols or effects skips a node
with a store instead of reading `ops`, which would box every element.
The public view is `array`.

</MemberCard>

<MemberCard>

##### FunctionInterface.\_numericStoreFloats {#_numericstorefloats}

```ts
readonly _numericStoreFloats: boolean;
```

Internal. Are the integer-valued elements of the numeric store floats?
`true` when a float computation produced the store (`2·L` with the
element `0.5` holds the float `1`): the operand at that position is
then a float, not `engine.number(store[i])`. `false` for `ce.list()`
and when there is no store.

</MemberCard>

<MemberCard>

##### FunctionInterface.\_machineFloats {#_machinefloats}

```ts
readonly _machineFloats: boolean | undefined;
```

Internal. The exactness of the integer-valued elements of a `List` of
machine numbers: `false` exact, `true` floats, `undefined` when the
list is not a list of machine numbers or mixes both kinds. See
`BoxedFunction._machineFloats`.

</MemberCard>

<MemberCard>

##### FunctionInterface.op1 {#op1}

```ts
readonly op1: Expression;
```

</MemberCard>

<MemberCard>

##### FunctionInterface.op2 {#op2}

```ts
readonly op2: Expression;
```

</MemberCard>

<MemberCard>

##### FunctionInterface.op3 {#op3}

```ts
readonly op3: Expression;
```

</MemberCard>

<MemberCard>

##### FunctionInterface.\_isLiteralData() {#_isliteraldata}

```ts
_isLiteralData(): boolean
```

Internal. Is this node written-out DATA: a canonical `List` or `Tuple`
bound to the standard library whose every element is a number literal,
a failed cell, or such a `List` or `Tuple` in turn? A failed cell is an
`Error` node with no symbol in it, and is data too. Such a node holds no
symbol and evaluates to itself. The answer is computed once per node.

</MemberCard>

### StringInterface {#stringinterface}

Narrowed interface for string expressions.

Obtained via `isString()`.

<MemberCard>

##### StringInterface.string {#string-3}

```ts
readonly string: string;
```

</MemberCard>

<MemberCard>

##### StringInterface.buffer {#buffer}

```ts
readonly buffer: Uint8Array;
```

The UTF-8 encoding of the string, as a byte buffer.

</MemberCard>

<MemberCard>

##### StringInterface.unicodeScalars {#unicodescalars}

```ts
readonly unicodeScalars: number[];
```

The Unicode scalar values (code points) of the string.

</MemberCard>

### CharacterInterface {#characterinterface}

Narrowed interface for a character expression — one NFC-normalized grapheme
cluster (UAX #29).

Obtained via `isCharacter()`.

`string` holds the cluster's content and is deliberately spelled the same as
`StringInterface.string`, so a consumer that only needs the text (the
`String` interpolation join, `StringJoin`) can read either kind through one
property without first deciding which it has.

<MemberCard>

##### CharacterInterface.string {#string-4}

```ts
readonly string: string;
```

The content of the character: exactly one grapheme cluster.

</MemberCard>

<MemberCard>

##### CharacterInterface.unicodeScalars {#unicodescalars-1}

```ts
readonly unicodeScalars: number[];
```

The Unicode scalar values (code points) of the cluster.

</MemberCard>

### TensorInterface {#tensorinterface}

Narrowed interface for tensor expressions.

Obtained via `isTensor()`.

<MemberCard>

##### TensorInterface.shape {#shape-4}

```ts
readonly shape: number[];
```

</MemberCard>

<MemberCard>

##### TensorInterface.rank {#rank-3}

```ts
readonly rank: number;
```

</MemberCard>

### CollectionInterface {#collectioninterface}

Narrowed interface for collection expressions.

Obtained via `isCollection()`.

#### Extended by

- [`IndexedCollectionInterface`](#indexedcollectioninterface)

<MemberCard>

##### CollectionInterface.isCollection {#iscollection-2}

```ts
readonly isCollection: true;
```

</MemberCard>

<MemberCard>

##### CollectionInterface.count {#count-3}

```ts
readonly count: number | bigint | undefined;
```

</MemberCard>

<MemberCard>

##### CollectionInterface.isFiniteCollection {#isfinitecollection-1}

```ts
readonly isFiniteCollection: boolean | undefined;
```

</MemberCard>

<MemberCard>

##### CollectionInterface.isEmptyCollection {#isemptycollection-1}

```ts
readonly isEmptyCollection: boolean | undefined;
```

</MemberCard>

<MemberCard>

##### CollectionInterface.isEnumerableCollection {#isenumerablecollection-1}

```ts
readonly isEnumerableCollection: boolean | undefined;
```

</MemberCard>

<MemberCard>

##### CollectionInterface.each() {#each-1}

```ts
each(): Generator<Expression>
```

</MemberCard>

<MemberCard>

##### CollectionInterface.contains() {#contains-2}

```ts
contains(rhs): boolean | undefined
```

####### rhs

[`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### CollectionInterface.subsetOf() {#subsetof-2}

```ts
subsetOf(other, strict): boolean | undefined
```

####### other

[`Expression`](#expression-5)

####### strict

`boolean`

</MemberCard>

### IndexedCollectionInterface {#indexedcollectioninterface}

Narrowed interface for indexed collection expressions (lists, vectors,
matrices, tuples).

Obtained via `isIndexedCollection()`.

#### Extends

- [`CollectionInterface`](#collectioninterface)

<MemberCard>

##### IndexedCollectionInterface.isIndexedCollection {#isindexedcollection-1}

```ts
readonly isIndexedCollection: true;
```

</MemberCard>

<MemberCard>

##### IndexedCollectionInterface.at() {#at-3}

```ts
at(index): Expression | undefined
```

####### index

`number`

</MemberCard>

<MemberCard>

##### IndexedCollectionInterface.indexWhere() {#indexwhere-2}

```ts
indexWhere(predicate): number | undefined
```

####### predicate

(`element`) => `boolean`

</MemberCard>

<MemberCard>

### ExpressionInput {#expressioninput}

```ts
type ExpressionInput = 
  | number
  | bigint
  | boolean
  | string
  | BigNum
  | Complex
  | MathJsonNumberObject
  | MathJsonStringObject
  | MathJsonSymbolObject
  | MathJsonFunctionObject
  | MathJsonDictionaryObject
  | readonly [MathJsonSymbol, ...ExpressionInput[]]
  | MathJsonExpression
  | Expression;
```

An expression input is a MathJSON expression which can include some
engine expression terms.

This is convenient when creating new expressions from portions
of an existing `Expression` while avoiding unboxing and reboxing.

</MemberCard>

### ObjectInterface {#objectinterface}

Narrowed interface for **object** expressions — the engine's one mutable
value kind (a reference to a record whose stored fields can be changed in
place).

Obtained via `isObject()`. The instance IS the heap record: host reference
identity of the expression is object identity, so every comparison tier
(`isSame`, `isEqual`, `isIdenticallyEqual`) answers `a === b` for objects,
and no code path may clone, rebuild or re-box one.

The members below are engine-internal (they are how the property-access
operators and the serialization walk reach the slots); user code reads and
writes fields through the language's property syntax, not through these.

Design: `docs/TYPE-SYSTEM.md`;
semantics: `docs/TYPE_SYSTEM_ROADMAP.md` Appendix B.

<MemberCard>

##### ObjectInterface.typeName {#typename}

```ts
readonly typeName: string;
```

The name of the nominal type this object was constructed with. The
resolved type itself is pinned on the instance and returned by `.type`;
this is the name that rides serialization (the `Object` provenance head
and `CircularReference` markers).

</MemberCard>

<MemberCard>

### ArrayCells {#arraycells}

```ts
type ArrayCells = 
  | Uint8Array
  | Int8Array
  | Uint16Array
  | Int16Array
  | Uint32Array
  | Int32Array
  | Float64Array
  | Expression[];
```

The storage of the cells of a mutable array: a typed array for machine
cells (four bytes for each cell of a tuple of four bytes), an array of
evaluated expressions for every other cell type.

</MemberCard>

### ArrayInterface {#arrayinterface}

Narrowed interface for a **mutable array**, a value of type `array<T>`.

Obtained via `isMutableArray()`, or made by the host with `ce.array()`. As
for an object, the instance is the array: two arrays are equal only when
they are the same instance, and the hash does not change when a cell
changes.

A host reads and writes the cells through [cells](#cells):

```ts
const a = ce.array(new Uint8Array(4 * width * height), 'Pixel');
const bytes = a.cells as Uint8Array;
bytes[0] = 255; // the red byte of the first pixel
a.noteStore();
```

The engine does not check what the host guarantees, and the result is
unspecified when one of these does not hold:

- one typed array, or two views that overlap, are the cells of one array
  only;
- every cell of a storage that the host adopted or wrote holds a value of
  the cell type;
- the host calls [noteStore](#notestore) after it writes through `cells`, before
  any code of the engine reads the array;
- a storage keeps its length while it is the cells of an array: the host
  does not detach or transfer its buffer.

Design: `docs/plans/2026-11-25-mutable-arrays-spec.md`.

<MemberCard>

##### ArrayInterface.cells {#cells}

```ts
readonly cells: 
  | Uint8Array<ArrayBufferLike>
  | Int8Array<ArrayBufferLike>
  | Uint16Array<ArrayBufferLike>
  | Int16Array<ArrayBufferLike>
  | Uint32Array<ArrayBufferLike>
  | Int32Array<ArrayBufferLike>
  | Float64Array<ArrayBufferLike>
  | readonly Expression[];
```

The storage, by reference. A typed array for machine cells, with four
bytes for each cell of a tuple of four bytes (its length is then
`4 × count`), and a read-only array of expressions for expression cells.

The storage is valid until the array changes its length, or
`swapCells()` or `Swap` runs. Read `cells` at each use, and keep no copy
of the reference between two calls.

</MemberCard>

<MemberCard>

##### ArrayInterface.version {#version}

```ts
readonly version: number;
```

The change signal: two reads at the same version saw the same cells. A
larger version does not prove that a cell changed.

</MemberCard>

<MemberCard>

##### ArrayInterface.count {#count-4}

```ts
readonly count: number;
```

The number of cells.

</MemberCard>

<MemberCard>

##### ArrayInterface.cellType {#celltype}

```ts
readonly cellType: BoxedType;
```

The cell type: `T` for an `array<T>`.

</MemberCard>

<MemberCard>

##### ArrayInterface.stale {#stale}

```ts
readonly stale: boolean;
```

True from a [markStale](#markstale) until its fetch runs.

</MemberCard>

<MemberCard>

##### ArrayInterface.noteStore() {#notestore}

```ts
noteStore(): void
```

A host that wrote cells through [cells](#cells) calls it once after its
writes. It does what a store does after its write: it increments the
version, invalidates the results that the engine computed from the
array, and reports one state event.

</MemberCard>

<MemberCard>

##### ArrayInterface.swapCells() {#swapcells}

```ts
swapCells<S>(storage): S
```

Take the typed array `storage` as the cells, and return the cells that
the array had. `storage` has the storage kind and the length of the
current cells. It counts as a store (the version, the results of the
engine, one state event). A host that computes a frame in a second
buffer exchanges the two with no copy:

```ts
let back = new Uint8Array(frame.cells.length);
// ... write the next frame in `back`
back = frame.swapCells(back);
```

The result has the type of `storage`, so that the exchange above
type-checks. The value is the typed array that the array held: when
`storage` is an instance of a subclass (a Node `Buffer`), the cells
returned are a plain typed array of the same kind, not an instance of
that subclass.

Throws a `TypeError` for a storage of another kind or another length,
for an array of expression cells, for a view of a `SharedArrayBuffer`,
and for a view of a resizable `ArrayBuffer`.

• S extends 
  \| `Uint8Array`\<`ArrayBufferLike`\>
  \| `Int8Array`\<`ArrayBufferLike`\>
  \| `Uint16Array`\<`ArrayBufferLike`\>
  \| `Int16Array`\<`ArrayBufferLike`\>
  \| `Uint32Array`\<`ArrayBufferLike`\>
  \| `Int32Array`\<`ArrayBufferLike`\>
  \| `Float64Array`\<`ArrayBufferLike`\>

####### storage

`S`

</MemberCard>

<MemberCard>

##### ArrayInterface.markStale() {#markstale}

```ts
markStale(fetch): void
```

Record that the cells are out of date, for storage that the host keeps
elsewhere (a texture of the GPU): `fetch` gives the latest cells. It
counts as a store (the version, the results of the engine, one state
event), and writes no cell.

At the next access of the cells, the engine clears the mark and calls
`fetch(array)` once. The accesses are a read, a store, a `Swap`, a
`ListFrom`, a slice and the serialization of the cells in the engine,
the getter [cells](#cells), and compiled code, which tests the mark of
each array it reads or stores when `run()` starts, after each call of
a function of the host and after each construction of an array, not
in its loops: an array of its inputs, one that a value of a name holds,
and one that entered the code in the same call of `run()` (one that it
made, or that a name it assigns held after a call of the host), also
when only a local holds it. Compiled code that reads, stores and
exchanges no cell tests no mark: an array that it gives to a function of
the host, or returns, stays stale until the next access of its cells.
The rule is of the whole compiled function: one that accesses a cell
anywhere, also before a call of the host, tests at each of those points.
When no array of the engine is stale, each
of those points costs one test, and each array that is made or read
after a call of the host costs one add to a `WeakSet`, so that it can be
found when it is marked later. The fetch writes the latest
cells through [cells](#cells), or gives new storage with
[swapCells](#swapcells). A [noteStore](#notestore) or `swapCells()` made by the
fetch is part of the store that `markStale()` was, and does not
increment the version again. A fetch that throws leaves the array
stale, with the same fetch, unless it marked the array again or gave
the cells: the next access calls it again.

An array of expression cells throws a `TypeError`: a fetch has no
machine cells to write.

A second call before the fetch replaces the pending fetch. A
`swapCells()` while the array is stale clears the mark and calls no
fetch: the host gave the cells. A `markStale()` made while compiled code
runs between two of its tests (from another thread or a timer) is
unspecified.

```ts
// The GPU wrote the next generation into a texture.
board.markStale((a) => readPixelsInto(a.cells as Uint8Array));
```

####### fetch

(`array`) => `void`

</MemberCard>

<MemberCard>

### ReplaceOptions {#replaceoptions}

```ts
type ReplaceOptions = {
  recursive: boolean;
  once: boolean;
  useVariations: boolean;
  matchPermutations: boolean;
  iterationLimit: number;
  form: FormOption;
  direction: "left-right" | "right-left";
};
```

Options for `Expression.replace()`.

</MemberCard>

<MemberCard>

### CanonicalForm {#canonicalform}

```ts
type CanonicalForm = 
  | "InvisibleOperator"
  | "Number"
  | "Multiply"
  | "Add"
  | "Power"
  | "Divide"
  | "Flatten"
  | "Order";
```

Canonical normalization transforms.

</MemberCard>

<MemberCard>

### CanonicalOptions {#canonicaloptions}

```ts
type CanonicalOptions = 
  | boolean
  | CanonicalForm
  | CanonicalForm[];
```

</MemberCard>

<MemberCard>

### FormOption {#formoption}

```ts
type FormOption = 
  | "canonical"
  | "structural"
  | "raw"
  | CanonicalForm
  | CanonicalForm[];
```

Controls how expressions are created.

</MemberCard>

<MemberCard>

### Metadata {#metadata}

```ts
type Metadata = {
  latex: string;
  wikidata: string;
  sourceOffsets: [start: number, end: number];
};
```

Metadata that can be associated with a MathJSON expression.

</MemberCard>

## Pattern Matching

<MemberCard>

### Substitution {#substitution}

```ts
type Substitution<T> = KernelSubstitution<T>;
```

A substitution describes the values of the wildcards in a pattern so that
the pattern is equal to a target expression.

A substitution can also be considered a more constrained version of a
rule whose `match` is always a symbol.

#### Type Parameters

• T = [`ExpressionInput`](#expressioninput)

</MemberCard>

<MemberCard>

### BoxedSubstitution {#boxedsubstitution}

```ts
type BoxedSubstitution<T> = KernelBoxedSubstitution<T>;
```

#### Type Parameters

• T = [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

### PatternMatchOptions {#patternmatchoptions}

```ts
type PatternMatchOptions<T> = KernelPatternMatchOptions<T>;
```

Control how a pattern is matched to an expression.

#### Type Parameters

• T = [`Expression`](#expression-5)

</MemberCard>

## Rules

<MemberCard>

### RuleReplaceFunction {#rulereplacefunction}

```ts
type RuleReplaceFunction = KernelRuleReplaceFunction<Expression>;
```

Rule replacement callback specialized to boxed expressions.

</MemberCard>

<MemberCard>

### RuleConditionFunction {#ruleconditionfunction}

```ts
type RuleConditionFunction = KernelRuleConditionFunction<Expression, IComputeEngine>;
```

Rule condition callback with access to the compute engine.

</MemberCard>

<MemberCard>

### RuleFunction {#rulefunction}

```ts
type RuleFunction = KernelRuleFunction<Expression>;
```

Dynamic rule callback.

</MemberCard>

<MemberCard>

### Rule {#rule}

```ts
type Rule = KernelRule<Expression, ExpressionInput, IComputeEngine>;
```

Rule declaration specialized to boxed expression and compute engine types.

</MemberCard>

<MemberCard>

### RulePurpose {#rulepurpose}

```ts
type RulePurpose = "simplify" | "transform" | "expand";
```

The purpose of a rule determines how its result is treated by
the simplification cost policy:

- `'simplify'`: the result must pass the cost gate (the default;
  today's behavior — results that grow the expression are discarded).
- `'transform'`: a mathematically-preferred rewrite; exempt from the
  cost gate (accepted by `simplify()` even if structurally larger).
- `'expand'`: growth-by-design (series, argument expansion); skipped by
  `simplify()`, but reachable via `expr.replace()` and future expand APIs.

</MemberCard>

<MemberCard>

### ExplainOperation {#explainoperation}

```ts
type ExplainOperation = "simplify" | "solve" | "D" | "Integrate";
```

The operation that an `Explanation` traces. See `expr.explain()`.

</MemberCard>

<MemberCard>

### ExplainVerbosity {#explainverbosity}

```ts
type ExplainVerbosity = "default" | "all";
```

How much of the raw rule trace `expr.explain()` returns:

- `'default'`: curated — bookkeeping steps (driver-internal markers) and
  no-op steps are filtered out.
- `'all'`: the raw, uncurated chain (for rule authors and debugging).

</MemberCard>

## Assumptions

<MemberCard>

### ExpressionMapInterface {#expressionmapinterface}

```ts
type ExpressionMapInterface<U> = KernelExpressionMapInterface<U, Expression>;
```

Map-like interface keyed by boxed expressions.

#### Type Parameters

• U

</MemberCard>

<MemberCard>

### Assumption {#assumption}

```ts
type Assumption = KernelAssumption<Expression, IComputeEngine>;
```

Assumption predicates bound to this compute engine.

</MemberCard>

<MemberCard>

### FactSubject {#factsubject}

```ts
type FactSubject = KernelFactSubject<BoxedValueDefinition>;
```

One subject of an assumption, specialized to this engine/runtime model.

</MemberCard>

<MemberCard>

### FactRecord {#factrecord}

```ts
type FactRecord = KernelFactRecord<BoxedValueDefinition>;
```

One assertion recorded by `assume()`, specialized to this engine/runtime
model. The assumptions store maps a normalized fact to a list of these.

</MemberCard>

<MemberCard>

### AssumeResult {#assumeresult}

```ts
type AssumeResult = 
  | "internal-error"
  | "not-a-predicate"
  | "contradiction"
  | "tautology"
  | "ok";
```

</MemberCard>

## Compiling

<MemberCard>

### CompiledType {#compiledtype}

```ts
type CompiledType = boolean | number | string | object;
```

</MemberCard>

<MemberCard>

### JSSource {#jssource}

```ts
type JSSource = string;
```

</MemberCard>

<MemberCard>

### CompiledExpression {#compiledexpression}

```ts
type CompiledExpression = {
  evaluate: (scope) => number | Expression;
};
```

</MemberCard>

<MemberCard>

### OperatorCompileContext {#operatorcompilecontext}

```ts
type OperatorCompileContext = {
  language: string;
  typeOf: (expr) => Type;
  inherited: OperatorCompileHandler;
};
```

The context passed to an operator [OperatorCompileHandler](#operatorcompilehandler).

</MemberCard>

<MemberCard>

### OperatorCompileHandler {#operatorcompilehandler}

```ts
type OperatorCompileHandler = (args, compile, context) => Expression | undefined;
```

A compilation handler for an operator, set on an `OperatorDefinition`. It
receives the (canonical) operands, a `compile` callback and the
compilation `context` (branch on `context.language`), and returns:

- `undefined` (a `null` or an empty string from untyped JavaScript is
  treated the same): the library's compilation of this operator.
- an `Expression`: it is compiled in place of the node, with the
  library's definitions. A node of the expression that the handler
  created is compiled with no compile handler consulted, whatever its
  operator (an `At` in the result of a handler of `At` is the library's
  `At`). A node under the operands the handler received (the same
  object), found in the result, is compiled as usual, handlers
  consulted. Reuse the objects you were given: a copy of an operand
  (rebuilt from its JSON) is a created node, and an operator inside it no
  longer gets its handler. A result that holds the node itself declines.

The compilation of the node declines when the handler returns text (a
handler that writes code text is not supported since 0.194.0), calls the
`compile` callback, or throws. The callback is kept so that `context`
stays the third argument.

The handler can be called more than once for one node in one
compilation: it must be a pure function of its operands and context for
the duration of a `compile()` call.

```ts
const def = ce.lookupDefinition('Twice');
if (def && 'operator' in def)
  def.operator.compile = ([x]) => ce.box(['Multiply', 2, x]);
```

</MemberCard>

## Definitions

<MemberCard>

### EvaluateHandlerOptions {#evaluatehandleroptions}

```ts
type EvaluateHandlerOptions = Partial<EvaluateOptions> & {
  engine: ComputeEngine;
  expression: Expression;
  precision: number;
  effects: EffectHandlers;
};
```

The `options` argument passed to an `evaluate` / `evaluateAsync` handler.

#### EvaluateHandlerOptions.expression?

```ts
expression?: Expression;
```

The canonical expression node being evaluated.

Its `ops` are the **raw** operands: canonical and bound, but
**pre-numericization** — the same objects the `type` handler sees. The
handler's first parameter, by contrast, holds the *evaluated* operands,
which under `numericApproximation` have already been turned into floats.

That makes this the handler's only access to the operands' exactness. For
example `Power` reads the exact rational `p/q` of its exponent from
`expression.op2` to decide the branch of a negative base — under `.N()`
the exponent it receives as an operand is a double, from which `p/q`
can only be guessed.

**`expression.ops[i]` is NOT in general the provenance of `ops[i]`.** The
evaluated operands come from `holdMap`, which reindexes them: it FLATTENS
an associative operator (`f(a, f(b, c))` arrives as three operands, one
more than the node has), it UNWRAPS `ReleaseHold` (so `expression.ops[i]`
is the wrapper, not what was evaluated), and it DROPS an operand whose
evaluation yields nothing. The correspondence holds only for a
non-associative operator with no `ReleaseHold` and no dropped operand — so
a handler that indexes into `expression.ops` must treat
`expression.ops.length !== ops.length` as "no provenance" and fall back to
what it can compute from the evaluated operands alone.

**On a `lazy: true` operator there is no contrast to draw**: `holdMap`
returns the operands unchanged, so the handler's first parameter is raw
and held too — and, on the box/parse routes, not even canonicalized (see
the lazy-operator trap in `ARCHITECTURE.md`: such a handler must canonicalize
each held operand it consumes).

Read-only: do not mutate it, and do not assume it is present (a handler
invoked outside the evaluation driver may not receive one).

#### EvaluateHandlerOptions.precision?

```ts
precision?: number;
```

The number of significant digits the caller asked for, when
`numericApproximation` is `true`. `undefined` when
`numericApproximation` is `false`: an exact evaluation has no precision.

- Inside `N(x, p)`, it is `p` for the evaluation of `x` and of every
  expression evaluated inside it, also when `p` is lower than the
  precision of the engine (then `N` computes at the precision of the
  engine and rounds the result to `p` digits).
- Otherwise (`x.N()`, `N(x)`, `evaluate({ numericApproximation: true })`)
  it is `ce.precision`, the precision of the engine.

A handler can use it to compute to the requested number of digits
without reading `ce.precision`. `N(x, p)` with a `p` greater than the
precision of the engine computes at `p` digits plus guard digits for the
time of the call and restores the precision of the engine after it; on
the asynchronous route the raised precision travels with the evaluation
(`EvaluateOptions._precisionWindow`).

#### EvaluateHandlerOptions.effects

```ts
effects: EffectHandlers;
```

The host capabilities of THIS evaluation: the `ce.effects` registry as it
was when the evaluation started. A handler that reaches a host capability
reads it from here, never from `ce.effects`, so that a change of registry
made while the evaluation runs — or made for a different, concurrent
asynchronous evaluation — has no effect on it.

A handler may use a capability only if its operator declares the
corresponding effect label: `options.effects.console` requires `console`
in the signature. A `null` handler is a denial: return
`ce.error(['capability-denied', '<capability>'])`.

</MemberCard>

<MemberCard>

### ValueDefinition {#valuedefinition}

```ts
type ValueDefinition = BaseDefinition & {
  holdUntil: "never" | "evaluate" | "N";
  type:   | Type
     | TypeString
     | BoxedType;
  inferred: boolean;
  effectsDeclared: boolean;
  value:   | LatexString
     | ExpressionInput
     | ((ce) => Expression | null);
  macro: MathJsonExpression;
  eq: (a) => boolean | undefined;
  neq: (a) => boolean | undefined;
  cmp: (a) => "=" | ">" | "<" | undefined;
  collection: CollectionHandlers;
  subscriptEvaluate: (subscript, options) => Expression | undefined;
};
```

A bound symbol (i.e. one with an associated definition) has either a type
(e.g. ∀ x ∈ ℝ), a value (x = 5) or both (π: value = 3.14... type = 'real').

#### ValueDefinition.inferred

```ts
inferred: boolean;
```

If true, the type is inferred, and could be adjusted later
as more information becomes available or if the symbol is explicitly
declared.

#### ValueDefinition.effectsDeclared

```ts
effectsDeclared: boolean;
```

Annotation provenance on the EFFECTS axis of a function-typed
declaration (`docs/EFFECTS-MODEL.md`, "Annotation provenance") — the
effects-axis analog of `inferred`.

True when the author STATED the arrow's effects: a non-empty specifier
(`(number) scope -> number`), or the `pure` keyword — which denotes the
same empty set a bare arrow does, so the type alone cannot tell them
apart. A bare arrow leaves effects on the inferred track: assigning a
body re-stamps them freely. A stated set is a CONTRACT: every assigned
body must satisfy `inferred ⊆ declared`.

Set by `ce.declare()` from the parsed declaration; not normally written
by hand.

#### ValueDefinition.value

```ts
value: 
  | LatexString
  | ExpressionInput
  | ((ce) => Expression | null);
```

`value` can be a JS function since for some constants, such as
`Pi`, the actual value depends on the `precision` setting of the
`ComputeEngine` and possible other environment settings

#### ValueDefinition.macro

```ts
macro: MathJsonExpression;
```

The raw MathJSON body of a macro: `ce.declare('A', { macro: body })`.

A macro has no value and the type `unknown`. A name of the input
(MathJSON or LaTeX) that resolves to the macro where it is boxed in a
canonical or a structural form is replaced by the body, boxed at that
place, in the scope of the occurrence and in the same form. A position
that takes a name (a parameter, an index, the variable of `D`, the
target of `Assign`) is not an occurrence, and a symbol made with
`ce.symbol()` is not expanded. A parameter, an index or a local of the
same name hides the macro.

A definition with `macro` takes no other field.

#### ValueDefinition.subscriptEvaluate?

```ts
subscriptEvaluate?: (subscript, options) => Expression | undefined;
```

Custom evaluation handler for subscripted expressions of this symbol.
Called when evaluating `Subscript(symbol, index)`.

###### subscript

[`Expression`](#expression-5)

The subscript expression (already evaluated)

###### options

Contains the compute engine and evaluation options

####### engine

[`ComputeEngine`](#computeengine)

####### numericApproximation?

`boolean`

</MemberCard>

### SequenceDefinition {#sequencedefinition}

Definition for a sequence declared with `ce.declareSequence()`.

A sequence is defined by base cases and a recurrence relation.

#### Example

```typescript
// Fibonacci sequence
ce.declareSequence('F', {
  base: { 0: 0, 1: 1 },
  recurrence: 'F_{n-1} + F_{n-2}',
});
ce.parse('F_{10}').evaluate();  // → 55
```

<MemberCard>

##### SequenceDefinition.variable? {#variable}

```ts
variable?: string;
```

Index variable name for single-index sequences, default 'n'.
For multi-index sequences, use `variables` instead.

</MemberCard>

<MemberCard>

##### SequenceDefinition.variables? {#variables}

```ts
variables?: string[];
```

Index variable names for multi-index sequences.
Example: `['n', 'k']` for Pascal's triangle `P\_{n,k}`

If provided, this takes precedence over `variable`.

</MemberCard>

<MemberCard>

##### SequenceDefinition.base {#base}

```ts
base: Record<number | string, number | Expression>;
```

Base cases as index → value mapping.

For single-index sequences, use numeric keys:
```typescript
base: { 0: 0, 1: 1 }  // F_0 = 0, F_1 = 1
```

For multi-index sequences, use comma-separated string keys:
```typescript
base: {
  '0,0': 1,    // Exact: P_{0,0} = 1
  'n,0': 1,    // Pattern: P_{n,0} = 1 for all n
  'n,n': 1,    // Pattern: P_{n,n} = 1 (diagonal)
}
```

Pattern keys use variable names to match any value. When the same
variable appears multiple times (e.g., 'n,n'), the indices must be equal.

</MemberCard>

<MemberCard>

##### SequenceDefinition.recurrence {#recurrence}

```ts
recurrence: string | Expression;
```

Recurrence relation as LaTeX string or Expression

</MemberCard>

<MemberCard>

##### SequenceDefinition.memoize? {#memoize}

```ts
memoize?: boolean;
```

Whether to memoize computed values (default: true)

</MemberCard>

<MemberCard>

##### SequenceDefinition.domain? {#domain-1}

```ts
domain?: 
  | {
  min: number;
  max: number;
 }
  | Record<string, {
  min: number;
  max: number;
}>;
```

Valid index domain constraints.

For single-index sequences:
```typescript
domain: { min: 0, max: 100 }
```

For multi-index sequences, use per-variable constraints:
```typescript
domain: { n: { min: 0 }, k: { min: 0 } }
```

</MemberCard>

<MemberCard>

##### SequenceDefinition.constraints? {#constraints}

```ts
constraints?: string | Expression;
```

Constraint expression for multi-index sequences.
The expression should evaluate to a boolean/numeric value.
If it evaluates to false or 0, the subscript is considered out of domain.

Example: `'k <= n'` for Pascal's triangle (only valid when k ≤ n)

</MemberCard>

### SequenceStatus {#sequencestatus}

Status of a sequence definition.

<MemberCard>

##### SequenceStatus.status {#status-1}

```ts
status: "complete" | "pending" | "not-a-sequence";
```

Status of the sequence:
- 'complete': Both base case(s) and recurrence defined
- 'pending': Waiting for base case(s) or recurrence
- 'not-a-sequence': Symbol is not a sequence

</MemberCard>

<MemberCard>

##### SequenceStatus.hasBase {#hasbase}

```ts
hasBase: boolean;
```

Whether at least one base case is defined

</MemberCard>

<MemberCard>

##### SequenceStatus.hasRecurrence {#hasrecurrence}

```ts
hasRecurrence: boolean;
```

Whether a recurrence relation is defined

</MemberCard>

<MemberCard>

##### SequenceStatus.baseIndices {#baseindices}

```ts
baseIndices: (string | number)[];
```

Keys of defined base cases.
For single-index: numeric indices (e.g., [0, 1])
For multi-index: string keys including patterns (e.g., ['0,0', 'n,0', 'n,n'])

</MemberCard>

<MemberCard>

##### SequenceStatus.variable? {#variable-1}

```ts
variable?: string;
```

Index variable name if recurrence is defined (single-index)

</MemberCard>

<MemberCard>

##### SequenceStatus.variables? {#variables-1}

```ts
variables?: string[];
```

Index variable names if recurrence is defined (multi-index)

</MemberCard>

### SequenceInfo {#sequenceinfo}

Information about a defined sequence for introspection.

<MemberCard>

##### SequenceInfo.name {#name-1}

```ts
name: string;
```

The sequence name

</MemberCard>

<MemberCard>

##### SequenceInfo.variable? {#variable-2}

```ts
variable?: string;
```

Index variable name for single-index sequences (e.g., `"n"`)

</MemberCard>

<MemberCard>

##### SequenceInfo.variables? {#variables-2}

```ts
variables?: string[];
```

Index variable names for multi-index sequences (e.g., `["n", "k"]`)

</MemberCard>

<MemberCard>

##### SequenceInfo.baseIndices {#baseindices-1}

```ts
baseIndices: (string | number)[];
```

Base case keys.
For single-index: numeric indices
For multi-index: string keys including patterns

</MemberCard>

<MemberCard>

##### SequenceInfo.memoize {#memoize-1}

```ts
memoize: boolean;
```

Whether memoization is enabled

</MemberCard>

<MemberCard>

##### SequenceInfo.domain {#domain-2}

```ts
domain: 
  | {
  min: number;
  max: number;
 }
  | Record<string, {
  min: number;
  max: number;
}>;
```

Domain constraints.
For single-index: `{ min?, max? }`
For multi-index: per-variable constraints

</MemberCard>

<MemberCard>

##### SequenceInfo.cacheSize {#cachesize}

```ts
cacheSize: number;
```

Number of cached values

</MemberCard>

<MemberCard>

##### SequenceInfo.isMultiIndex {#ismultiindex}

```ts
isMultiIndex: boolean;
```

Whether this is a multi-index sequence

</MemberCard>

<MemberCard>

### Tri {#tri}

```ts
type Tri = boolean | undefined;
```

A three-valued fact about an operand: `true` (provably yes), `false`
(provably no), `undefined` (not decidable from what the descriptor knows).

</MemberCard>

<MemberCard>

### OperandFacts {#operandfacts}

```ts
type OperandFacts = {
  finite: Tri;
  sgn: Sign;
  closed: Tri;
  collection: Tri;
  finiteCollection: Tri;
  indexed: Tri;
  shape: readonly number[];
  elementType: Type;
};
```

The facts a `type` handler in the `'types'` shape may read about one
operand, beside the operand's type. Every fact is derived from pure
sources — the operand's type, a literal's value, a symbol's held value or
recorded assumptions, structural reads — never by canonicalizing,
declaring, or evaluating anything.

The set is deliberately minimal: a fact earns a field only when the
operand's TYPE cannot carry it. Anything the type proves is read off
`OperandDescriptor.type` directly — an error operand's type IS `'error'`
(so there is no `valid` field), and a literal's value, sign, and
finiteness normally travel in its value-carrying type. Each field below
merges the type channel with the pure value channel, so a handler reads
ONE place and never re-derives the combination; the doc of each field
names the residue that justifies it.

</MemberCard>

<MemberCard>

### OperandStructure {#operandstructure}

```ts
type OperandStructure = 
  | {
  kind: "symbol";
  name: string;
  lookupByName: false;
  system: boolean;
  inferred: boolean;
  local: boolean;
  free: true;
  captured: true;
 }
  | {
  kind: "string";
  text: string;
 }
  | {
  kind: "number";
  tier: Type;
  literal: 0 | 1;
  rational: readonly [bigint, bigint];
 }
  | {
  kind: "application";
  head: string;
  callee: OperandDescriptor;
  children: ReadonlyArray<OperandDescriptor>;
 }
  | {
  kind: "function-literal";
  parameters: ReadonlyArray<{
     name: string;
     annotated: Type;
     rest: boolean;
     optional: boolean;
     default: ParameterDefault;
    }>;
  body: OperandStructure;
 }
  | {
  kind: "tuple";
  arity: number;
  elements: ReadonlyArray<OperandDescriptor>;
 }
  | {
  kind: "list-literal";
  shape: readonly number[];
  elements: ReadonlyArray<OperandDescriptor>;
};
```

An inert, expression-free structural view of an operand, for `type`
handlers in the `'types'` shape that need more than the operand's type
(is it a symbol? a string literal? an application of which operator?).
Children appear as descriptors, so a handler can recurse without ever
holding an expression.

#### Type Declaration

\{
  `kind`: `"symbol"`;
  `name`: `string`;
  `lookupByName`: `false`;
  `system`: `boolean`;
  `inferred`: `boolean`;
  `local`: `boolean`;
  `free`: `true`;
  `captured`: `true`;
 \}

#### OperandStructure.lookupByName?

```ts
lookupByName?: false;
```

False when resolving this name in the current engine context would
select a different binding, or when this is a synthetic bound symbol.
Type handlers must then use the descriptor's own type rather than
derive a call or read a declaration by name.

#### OperandStructure.system?

```ts
system?: boolean;
```

Present (`true`) when the symbol resolves to the definition the
engine's SYSTEM scope binds under this name — the library constant
or operator, not a user or local declaration that shadows it. The
ring arms of `At` and `Subscript` read it: `Integers[k]` is a
quotient-ring adjunction only for the library `Integers`.

#### OperandStructure.inferred?

```ts
inferred?: boolean;
```

Present (`true`) when the symbol's recorded type was INFERRED
(subject to revision) rather than declared — the fact the
`Multiply` and `List`-fold handlers consult when deciding how much
to trust an operand's type. Lives on the structure node, not in
`OperandFacts`: it is a property of this symbol, not of a type.

#### OperandStructure.local?

```ts
local?: boolean;
```

Present (`true`) when the symbol is a block-local binding a `Block`
hoisted for a `let` or a block-introducing assignment, still waiting
for the statement that gives it a value. Such a local is not a
generic value, its type is simply not known yet: the handlers that
ask whether an operand may hold a list read it.

#### OperandStructure.free?

```ts
free?: true;
```

Present (`true`) when the symbol is free: it has no value, it is
not a constant and not a pattern wildcard (a name
that starts with `_`), and a scope of the current context other
than the system scope binds it, but not as a parameter of a
function literal, a local of a `Block` or the variable of a binder
(a `Sum` index). The `List` type handler reads a symbol of type
`unknown` as a number cell only when this is present: these are the
symbols that the canonical form of a literal list infers as
numbers.

#### OperandStructure.captured?

```ts
captured?: true;
```

Present (`true`) when the body of a function literal reads the
symbol, and the symbol has no value and is not a parameter of the
literal or a `let` local of the body (`isCapturedValuelessSymbol`).
When the body is evaluated, the symbol reads the value that an outer
scope holds at that time. A call of a function literal reads such a
symbol of type `unknown` as an operand that may hold a list.

\{
  `kind`: `"string"`;
  `text`: `string`;
 \}

\{
  `kind`: `"number"`;
  `tier`: [`Type`](#type-3);
  `literal`: `0` \| `1`;
  `rational`: readonly \[`bigint`, `bigint`\];
 \}

#### OperandStructure.tier

```ts
tier: Type;
```

The tier the literal contributes to a COMPOSITE type: `integer`,
`rational`, `real`, `complex`, `imaginary`, `nan`, `infinity`, or
the signed pair `+oo | -oo`. A literal's handler-visible type
(`type` on the descriptor) carries its value or an enclosing range;
a composite built from the literal — a tuple's component, a list's
element, a record's field — is a stored contract and carries the
tier instead, so a container handler reads it here and never
builds the literal type only to widen it away. Read off the value
(`numberLiteralTierType`, `boxed-expression/literal-tier.ts`).

#### OperandStructure.rational?

```ts
rational?: readonly [bigint, bigint];
```

The literal's exact value as a REDUCED fraction, when it is a
rational with no radical part: `[numerator, denominator]`, the
denominator positive. A literal's handler-visible type carries only
an outward-rounded range for a rational no double represents
exactly, so a handler that needs the exact terms (the parity of a
power's exponent denominator decides real against complex) reads
them here. Absent for a float, a complex, a radical, or a
non-finite literal.

\{
  `kind`: `"application"`;
  `head`: `string`;
  `callee`: [`OperandDescriptor`](#operanddescriptor);
  `children`: `ReadonlyArray`\<[`OperandDescriptor`](#operanddescriptor)\>;
 \}

#### OperandStructure.callee?

```ts
callee?: OperandDescriptor;
```

The callable's own contract when ambient lookup would select a
different binding. A held literal may also supply its body structure.
Derive this call through Apply rather than resolving head by name.

\{
  `kind`: `"function-literal"`;
  `parameters`: `ReadonlyArray`\<\{
     `name`: `string`;
     `annotated`: [`Type`](#type-3);
     `rest`: `boolean`;
     `optional`: `boolean`;
     `default`: [`ParameterDefault`](#parameterdefault);
    \}\>;
  `body`: [`OperandStructure`](#operandstructure);
 \}

#### OperandStructure.parameters

```ts
parameters: ReadonlyArray<{
  name: string;
  annotated: Type;
  rest: boolean;
  optional: boolean;
  default: ParameterDefault;
}>;
```

One entry per parameter operand, in order. `rest` marks the REST
parameter (`(a, ...rest) => …`): it is always the last entry, it
takes no annotation, and it binds a tuple of every argument from its
own position onwards rather than occupying one positional slot. A
consumer reading arity must therefore treat the entries before it as
the required count and admit any number after. `optional` marks a
parameter with a default value (`(x, k = 2) => x * k`), and
`default` is that value: a call may leave the parameter out, and
the parameter then receives its default. The parameters with a
default come after the required ones.

\{
  `kind`: `"tuple"`;
  `arity`: `number`;
  `elements`: `ReadonlyArray`\<[`OperandDescriptor`](#operanddescriptor)\>;
 \}

#### OperandStructure.elements

```ts
elements: ReadonlyArray<OperandDescriptor>;
```

One descriptor per component, in order.

\{
  `kind`: `"list-literal"`;
  `shape`: readonly `number`[];
  `elements`: `ReadonlyArray`\<[`OperandDescriptor`](#operanddescriptor)\>;
 \}

#### OperandStructure.elements

```ts
elements: ReadonlyArray<OperandDescriptor>;
```

One descriptor per top-level element, in order. A nested row is
itself a `list-literal` structure, reachable through its
descriptor's `structureOf()`.

</MemberCard>

<MemberCard>

### OperandDescriptor {#operanddescriptor}

```ts
type OperandDescriptor = {
  type: Type;
  facts: OperandFacts;
  structureOf: () => OperandStructure | undefined;
};
```

What a `type` handler in the `'types'` shape receives in place of an
operand expression: the operand's handler-visible type (a number
literal's value-carrying type included), a set of three-valued facts,
and an optional on-demand structural view. Descriptors carry no
expression, so a handler cannot canonicalize, declare, or evaluate its
operands while deriving a type — which is the point of the shape: type
derivation must not modify engine state.

Built by `describe()` (from a real operand) and `describeType()` (from a
type alone) in `boxed-expression/operand-descriptor.ts`; the design is
`docs/plans/2026-08-22-type-handlers-on-types.md` §5.1.

</MemberCard>

<MemberCard>

### ReadonlyDefinitionView {#readonlydefinitionview}

```ts
type ReadonlyDefinitionView = {
  value: Readonly<BoxedValueDefinition>;
  operator: Readonly<BoxedOperatorDefinition>;
};
```

The definition view a `'types'`-shape `type` handler gets from
`PureEngineView.lookupDefinition`: the tagged value/operator halves with
every own property readonly. The shallow `Readonly` is compile-time
protection against the direct field writes a type handler must never
perform (`def.operator.signature = …`); the runtime purity guard remains
the dynamic enforcement for anything the type system cannot see.

</MemberCard>

### PureEngineView {#pureengineview}

The read-only slice of the engine available to a `type` handler in the
`'types'` shape: enough to parse and resolve types, and to look up a
definition — none of the mutating surface (`declare`, `assign`, `box`,
`parse`, `evaluate`), and the definition lookup answers a read-only view
([ReadonlyDefinitionView](#readonlydefinitionview)). The full `ComputeEngine` satisfies this
interface structurally, so the restriction is compile-time only; the
runtime purity guard (`CE_TYPE_PURITY_GUARD`, always on under test) is
what enforces it dynamically.

<MemberCard>

##### PureEngineView.\_typeResolver {#_typeresolver}

```ts
readonly _typeResolver: TypeResolver;
```

</MemberCard>

<MemberCard>

##### PureEngineView.tolerance {#tolerance}

```ts
readonly tolerance: number;
```

The engine's numeric tolerance, a read-only configuration value a
membership handler consults (`Element` declines rather than refute a
near-match inside it).

</MemberCard>

<MemberCard>

##### PureEngineView.precision {#precision}

```ts
readonly precision: number;
```

The engine's precision, the number of significant digits of its
numeric calculations (`ComputeEngine.precision`): a handler that reads
a float literal reads it to the digits it was rounded to (the branch of
`Power` for a negative base and a float exponent).

</MemberCard>

<MemberCard>

##### PureEngineView.strict {#strict}

```ts
readonly strict: boolean;
```

True when the engine checks the types of operands when it boxes an
expression (`ComputeEngine.strict`). A handler that answers `error` for
an operand that the boxing check refuses reads it, so that a non-strict
engine keeps the unevaluated application.

</MemberCard>

<MemberCard>

##### PureEngineView.\_protocolRegistry {#_protocolregistry}

```ts
readonly _protocolRegistry: Readonly<Record<string, object>>;
```

The protocol registry, keyed by protocol name. Its records are typed
opaquely here because the record type lives in `types-engine.ts`,
which imports this file; the protocol readers in `engine-protocols.ts`
(`protocolOfName`, `protocolMemberSignature`,
`protocolPropertyTypeOfReceiver`) take this view and know the records'
real shape. Read-only from a handler.

</MemberCard>

<MemberCard>

##### PureEngineView.type() {#type-4}

```ts
type(type): BoxedType
```

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

</MemberCard>

<MemberCard>

##### PureEngineView.lookupDefinition() {#lookupdefinition}

```ts
lookupDefinition(id): ReadonlyDefinitionView | undefined
```

####### id

`string`

</MemberCard>

<MemberCard>

### TypeHandlerContext {#typehandlercontext}

```ts
type TypeHandlerContext = {
  engine: PureEngineView;
  derive: (operator, operands) => Type | undefined;
};
```

The context argument of a `type` handler in the `'types'` shape.

`derive(operator, operands)` is the recursive entry point a handler needs
to type an application it does not have in hand — the body of a mapping
literal over the source's element type, say. It runs the named operator's
own `type` handler on the given descriptors, falling back to the declared
(instantiated) signature result, and reads nothing but definitions and
types (`deriveApplicationType`, `boxed-expression/derive-application-type.ts`).
It answers `undefined` for an unknown operator.

</MemberCard>

<MemberCard>

### OperatorTypeHandlerOnTypes {#operatortypehandlerontypes}

```ts
type OperatorTypeHandlerOnTypes = (operands, context) => BoxedType | undefined;
```

The `type` handler of an operator definition: a function of operand
DESCRIPTORS. Such a handler never sees an operand expression, so
deriving a type cannot declare, canonicalize, or evaluate anything — the
state-purity contract of
`docs/plans/2026-08-22-type-handlers-on-types.md`. Under test, and with
`CE_TYPE_PURITY_GUARD` set elsewhere, a handler that writes engine state
throws.
Return a `BoxedType` (for example `context.engine.type('real')`), or
`undefined` to use the declared signature. Numeric literal cargo in a
boxed result is widened at the application boundary; intentional ranges
remain intact. Built-ins use `BoxedType.forResult()` to share that work.

</MemberCard>

<MemberCard>

### OperatorDerivativeHandler {#operatorderivativehandler}

```ts
type OperatorDerivativeHandler = (ops, options) => Expression | undefined;
```

A handler that gives one partial derivative of an operator.

- `ops` are the arguments of the application being differentiated, for
  example `[x^2, y]` for `F(x^2, y)`. They are canonical, not evaluated.
- `options.argument` is the 0-based index of the argument with respect
  to which the partial derivative is requested.

Return the partial derivative `∂F/∂(argument number options.argument)`
evaluated AT `ops`, for example `2·x^2` for the first partial of
`F(u, v) = u^2 + v` applied to `[x^2, y]`. Do not multiply by the
derivative of the argument: the chain rule is applied by the caller.

Return `undefined` when the partial derivative is not known. That
partial then stays symbolic, as `Apply(Derivative(F, 1, 0), x^2, y)`.

Do not call `.simplify()` on the result: the derivative is computed
inside the simplification of other expressions, and calling `.simplify()`
there can recurse without end.

</MemberCard>

<MemberCard>

### OperatorDerivative {#operatorderivative}

```ts
type OperatorDerivative = 
  | ReadonlyArray<ExpressionInput | Expression>
  | OperatorDerivativeHandler;
```

The value of the `derivative` key of an operator definition. It has one
of two forms:

1. **An array with one entry for each argument**. Entry `i` is a function
   literal (`["Function", body, ...parameters]`, as MathJSON or as an
   expression) with one parameter for each argument of the operator. It
   gives the partial derivative with respect to argument `i`, as a
   function of all the arguments. For `F(x, y) = x^2·y`:

   ```ts
   derivative: [
     ['Function', ['Multiply', 2, 'x', 'y'], 'x', 'y'],  // ∂F/∂x
     ['Function', ['Power', 'x', 2], 'x', 'y'],           // ∂F/∂y
   ]
   ```

   The array is used only for an application with as many arguments as
   the array has entries, and an entry is used only if its literal has
   one parameter for each argument. In any other case the partial
   derivatives stay symbolic.

2. **A handler**, see [OperatorDerivativeHandler](#operatorderivativehandler). Use it when the
   number of arguments varies, or when a partial derivative needs code.

In both forms the derivative of `F(g₁, …, gₙ)` with respect to `v` is
given by the chain rule: `Σᵢ ∂ᵢF(g₁, …, gₙ) · ∂gᵢ/∂v`. A partial
derivative is requested only for an argument that depends on `v`.

For an argument that is a point (a tuple or a list of tuples), the
product `∂ᵢF · ∂gᵢ/∂v` multiplies each coordinate. It is correct only
when the partial derivative is a number `c` (the Jacobian is `c·I`). When
the partial derivative is a point (a gradient) or is not given, the
derivative of the application stays unevaluated.

When the application is a number and an argument that depends on `v` is
a list or a point (a function declared `(list<number>) -> number`), the
partial derivative is a gradient and the product is never correct: the
derivative of the application stays unevaluated, whatever the key gives.

</MemberCard>

<MemberCard>

### ParameterDocumentation {#parameterdocumentation}

```ts
type ParameterDocumentation = 
  | string
  | {
  description: string;
  sample: string;
  keys: Readonly<Record<string, OptionKeyDocumentation>>;
};
```

The documentation of one parameter of an operator
(`OperatorDefinition.parameters`): a description in Markdown, a sample
value, and for a parameter that takes a dictionary of options, the
documentation of each key. A string is the description alone.

A sample is one line of Epsil source in the Epsil spelling (`[1, 2, 3]`,
`x => x^2`, `"crimson"`), of the type of its parameter. An editor shows
it as faint text in an empty argument; it is not part of the
description.

</MemberCard>

<MemberCard>

### OptionKeyDocumentation {#optionkeydocumentation}

```ts
type OptionKeyDocumentation = 
  | string
  | {
  type: string;
  description: string;
  sample: string;
  default: string;
};
```

The documentation of one key of a parameter that takes a dictionary of
options (`ParameterDocumentation.keys`). A string is the description
alone. `type` is a type string (`tuple<real, real>`); `sample` and
`default` are Epsil source.

</MemberCard>

### BaseDefinition {#basedefinition}

Metadata common to both symbols and functions.

<MemberCard>

##### BaseDefinition.description {#description}

```ts
description: string | string[];
```

If a string, a short description, about one line long.

Otherwise, a list of strings, each string a paragraph.

May contain Markdown.

</MemberCard>

<MemberCard>

##### BaseDefinition.keywords? {#keywords}

```ts
keywords?: string[];
```

Search keywords (synonyms, alternate names) used by
`ce.searchDefinitions()`. Not shown in documentation.

</MemberCard>

<MemberCard>

##### BaseDefinition.examples {#examples}

```ts
examples: string | string[];
```

A list of examples of how to use this symbol or operator.

Each example is one line of Epsil source — `Rationalize(1.75)` — that
evaluates on a fresh engine to a value worth showing. A trailing `//`
comment is allowed and is replaced by the value the example evaluates
to when the standard-library page is generated
(`scripts/build-library-docs.ts`); that page executes every example, so
one that stops evaluating fails the documentation build.

</MemberCard>

<MemberCard>

##### BaseDefinition.url {#url-2}

```ts
url: string;
```

A URL pointing to more information about this symbol or operator.

</MemberCard>

<MemberCard>

##### BaseDefinition.wikidata {#wikidata}

```ts
wikidata: string;
```

A short string representing an entry in a wikibase.

For example `"Q167"` is the [wikidata entry](https://www.wikidata.org/wiki/Q167)
for the `Pi` constant.

</MemberCard>

<MemberCard>

##### BaseDefinition.isConstant? {#isconstant}

```ts
readonly isConstant?: boolean;
```

If true, the value or type of the definition cannot be changed

</MemberCard>

<MemberCard>

### SymbolDefinition {#symboldefinition}

```ts
type SymbolDefinition = OneOf<[ValueDefinition, OperatorDefinition]>;
```

A table mapping symbols to their definition.

Symbols should be valid MathJSON symbols. In addition, the
following rules are recommended:

- Use only latin letters, digits and `-`: `/[a-zA-Z0-9-]+/`
- The first character should be a letter: `/^[a-zA-Z]/`
- Functions and symbols exported from a library should start with an uppercase letter `/^[A-Z]/`

</MemberCard>

<MemberCard>

### PartialSymbolDefinition {#partialsymboldefinition}

```ts
type PartialSymbolDefinition<T> = T extends unknown ? Partial<T> : never;
```

`Partial` distributed over the [SymbolDefinition](#symboldefinition) union (a plain
`Partial<A | B>` would merge the arms into one loose object type).

#### Type Parameters

• T = [`SymbolDefinition`](#symboldefinition)

</MemberCard>

<MemberCard>

### SymbolDefinitionInput {#symboldefinitioninput}

```ts
type SymbolDefinitionInput = 
  | PartialSymbolDefinition
  | BoxedOperatorDefinition;
```

A definition as `ce.declare()` accepts it: a partial definition, or the
boxed operator definition read back from `expr.operatorDefinition`.

Admitting the boxed definition is what lets an operator be re-declared
from its existing definition with some handlers replaced:

```ts
const sqrt = ce.expr('Sqrt').operatorDefinition!;
ce.declare('Sqrt', {
  ...sqrt,
  evaluate: (ops, options) => sqrt.evaluate!(ops, options),
});
```

</MemberCard>

### LibraryDefinition {#librarydefinition}

A library bundles symbol/operator definitions and declares dependencies on
other libraries. It carries no LaTeX dictionary entries: to parse or
serialize a new notation, pass a dictionary to the `LatexSyntax` given with
the `latexSyntax` constructor option, or add entries to a running engine
with `ce.latexSyntax.addEntries()`.

To load a custom library on a running engine, use `ce.loadLibrary()`.

Use with the `libraries` constructor option to load standard or custom
libraries:

```ts
const ce = new ComputeEngine({
  libraries: ['core', 'arithmetic', {
    name: 'custom',
    requires: ['arithmetic'],
    definitions: { G: { value: 6.674e-11, type: 'real', isConstant: true } },
  }],
});
```

<MemberCard>

##### LibraryDefinition.name {#name-4}

```ts
name: string;
```

Library identifier

</MemberCard>

<MemberCard>

##### LibraryDefinition.requires? {#requires}

```ts
requires?: string[];
```

Libraries that must be loaded before this one

</MemberCard>

<MemberCard>

##### LibraryDefinition.definitions? {#definitions}

```ts
definitions?: Readonly<{}> | Readonly<{}>[];
```

Symbol and operator definitions

</MemberCard>

### BaseCollectionHandlers {#basecollectionhandlers}

These handlers are the primitive operations that can be performed on
all collections, indexed or not.

#### Definitions

<MemberCard>

##### BaseCollectionHandlers.iterator {#iterator}

```ts
iterator: (collection) => 
  | Iterator<Expression, undefined, any>
  | undefined;
```

Return an iterator that iterates over the elements of the collection.

The order in which the elements are returned is not defined. Requesting
two iterators on the same collection may return the elements in a
different order.

</MemberCard>

#### Other

<MemberCard>

##### BaseCollectionHandlers.count {#count}

```ts
count: (collection) => number | bigint | undefined;
```

Return the number of elements in the collection.

An empty collection has a count of 0. An infinite collection has a count
of `Infinity`. Return `undefined` when the count cannot be determined.

A finite count that is not a safe integer (larger than
`Number.MAX_SAFE_INTEGER`) cannot be held exactly by a `number`: return
it as a `bigint`. A handler can also return a `bigint` for a smaller
count: `expr.count` always converts a count that is a safe integer to a
`number`.

</MemberCard>

<MemberCard>

##### BaseCollectionHandlers.isEmpty? {#isempty}

```ts
isEmpty?: (collection) => boolean | undefined;
```

Optional flag to quickly check if the collection is empty, without having to count exactly how may elements it has (useful for lazy evaluation).

</MemberCard>

<MemberCard>

##### BaseCollectionHandlers.isFinite? {#isfinite}

```ts
isFinite?: (collection) => boolean | undefined;
```

Optional flag to quickly check if the collection is finite, without having to count exactly how many elements it has (useful for lazy evaluation).

</MemberCard>

<MemberCard>

##### BaseCollectionHandlers.isEnumerable? {#isenumerable}

```ts
isEnumerable?: (collection) => boolean | undefined;
```

Optional predicate answering whether `iterator()` will actually produce
this collection's elements — the cheap way to tell an EMPTY collection
from one that merely cannot be walked, which are otherwise
indistinguishable (both yield nothing).

Return `false` when the elements have no computable value in the current
state: symbolic bounds (`Range(a, b)`, `Linspace(a, 1, 3)`, a symbolic
repeat count), or a source that is itself not enumerable. Return
`undefined` only when it cannot be decided without evaluating.

Implementations must be O(1) and must NOT consult `count`, `isEmpty` or
`isFinite` on themselves, nor walk the collection: a wrapper answers by
reading its source's `isEnumerableCollection`, so a chain costs one call
per level. (Reading the emptiness facets instead is exponential in the
chain depth — each read re-enters the next `isEmpty` down.)

Default when the handler is ABSENT: `true` (an operator with a
`collection` block can enumerate its elements). A handler that IS declared
owns all three states — returning `undefined` from it means "cannot tell
cheaply" and does not fall back to the default.

</MemberCard>

<MemberCard>

##### BaseCollectionHandlers.isCollection? {#iscollection}

```ts
isCollection?: (collection) => boolean;
```

Optional predicate for operators whose collection-ness depends on their
operands, e.g. `If(cond, value)`, which is a collection exactly when
`value` is one.

Returning `false` reports the expression as a scalar, as if it had no
collection handlers at all.

Default: `true` (an operator with a `collection` block is a collection).

</MemberCard>

<MemberCard>

##### BaseCollectionHandlers.isLazy? {#islazy}

```ts
isLazy?: (collection) => boolean;
```

Return `true` if the collection is lazy, `false` otherwise.
If the collection is lazy, it means that the elements are not
computed until they are needed, for example when iterating over the
collection.

Default: `false`. A collection is eager unless its definition says
otherwise: the elements of a `List` are already materialized operands,
so nothing is deferred. Lazy collections such as `Range` or `Map` declare
this handler to opt in.

</MemberCard>

<MemberCard>

##### BaseCollectionHandlers.elementMemo? {#elementmemo}

```ts
elementMemo?: boolean;
```

Opt this operator's instances into per-instance element memoization: a
complete walk of an unmodified instance is served from a cached prefix
on subsequent walks (`boxed-expression/collection-element-memo.ts`).

Set it on lazy operators that evaluate a function per element (`Map`,
`Filter`, `Tabulate`, …), where re-deriving an element is expensive.
Leave it off structural reindexers (`Take`, `Reverse`, `Zip`, …), which
re-serve their source's elements cheaply — when the source is itself a
flagged instance, the source's own memo already absorbs the cost.

Default: `false`

</MemberCard>

<MemberCard>

##### BaseCollectionHandlers.callsCallbackOnRead? {#callscallbackonread}

```ts
callsCallbackOnRead?: boolean;
```

Set on a lazy operator that calls a function operand when its elements
are read, not when it is evaluated (`Map`, `Filter`, `Tabulate`, …).
An instance created during a function call keeps the evaluation
context of that call, and each read of the instance runs in it, so that
a name that the callback reads by its binding in the context (the symbol
default `d` of a parameter `(x, k = d) => x * k`) has the value it had in
the call, also when the instance is read after the call has returned
(`boxed-expression/lazy-view-context.ts`).

Leave it off an operator that calls its function operand when it is
evaluated (`Reduce`, `Sort`), and off an operator with no function
operand.

Default: `false`

</MemberCard>

<MemberCard>

##### BaseCollectionHandlers.contains? {#contains}

```ts
contains?: (collection, target) => boolean | undefined;
```

Return `true` if the target expression is in the collection,
`false` otherwise.

Return `undefined` if the membership cannot be determined.

</MemberCard>

<MemberCard>

##### BaseCollectionHandlers.countOf? {#countof}

```ts
countOf?: (collection, target) => number | bigint | undefined;
```

Return the number of elements of the collection that are structurally
the same as `target` (the `isSame()` comparison), without a walk of the
collection. `Count(xs, v)` reads it.

Give this handler when the collection can have more elements than a
walk can visit (a combinatorial generator such as `Permutations` has
`n!` elements): without it, `Count(xs, v)` walks every element. A count
that is not a safe integer is returned as a `bigint`.

Return `undefined` when the count cannot be computed without a walk.
The answer must be the one a walk that compares each element with
`isSame()` gives.

</MemberCard>

<MemberCard>

##### BaseCollectionHandlers.subsetOf? {#subsetof}

```ts
subsetOf?: (collection, other, strict) => boolean | undefined;
```

Return `true` if all the elements of `collection` are in `other` — that
is, `collection` ⊆ `other`. The RECEIVER is the candidate subset, matching
the public `Expression.subsetOf(other, strict)` method that dispatches
here. Both `collection` and `other` are collections.

If strict is `true`, the subset must be strict, that is, `other` must have
an element that `collection` does not.

Return `undefined` if the subset relation cannot be determined. A handler
that cannot see far enough to answer must return `undefined` rather than
`false`: `false` is read as a proof that the relation does NOT hold.

</MemberCard>

<MemberCard>

##### BaseCollectionHandlers.eltsgn? {#eltsgn}

```ts
eltsgn?: (collection) => Sign | undefined;
```

Return the sign of all the elements of the collection.

</MemberCard>

<MemberCard>

##### BaseCollectionHandlers.elttype? {#elttype}

```ts
elttype?: (collection) => Type | undefined;
```

Return the widest type of all the elements in the collection

</MemberCard>

### IndexedCollectionHandlers {#indexedcollectionhandlers}

These additional collection handlers are applicable to indexed
collections only.

The elements of an indexed collection can be accessed by index, and
the order of the elements is defined.

<MemberCard>

##### IndexedCollectionHandlers.at {#at}

```ts
at: (collection, index) => Expression | undefined;
```

Return the element at the specified index.

The first element is `at(1)`, the last element is `at(-1)`.

If the index is &lt;0, return the element at index `count() + index + 1`.

The index can also be a string, for example for records. There is no
handler that enumerates the valid string keys: a handler that accepts
them decides which ones it recognizes, and returns `undefined` for the
rest.

If the index is invalid, return `undefined`.

</MemberCard>

<MemberCard>

##### IndexedCollectionHandlers.indexWhere {#indexwhere}

```ts
indexWhere: (collection, predicate) => number | undefined;
```

Return the index of the first element that matches the predicate.

If no element matches the predicate, return `undefined`.

</MemberCard>

<MemberCard>

##### IndexedCollectionHandlers.atBigint? {#atbigint}

```ts
atBigint?: (collection, index) => Expression | undefined;
```

Return the element at a 1-based position given as a `bigint`.

The position is positive. A negative position is converted before the
call: it counts from the end, so it is `count + index + 1`.

`at()` takes a `number`, which cannot hold a position larger than
`Number.MAX_SAFE_INTEGER` exactly. Give this handler when the collection
can have more elements than that (its `count` can be a `bigint`): it is
used for such a position, and for a negative position when the count is
a `bigint`. Without it, these positions have no element.

If the position is outside the collection, return `undefined`.

</MemberCard>

<MemberCard>

##### IndexedCollectionHandlers.indexOf? {#indexof}

```ts
indexOf?: (collection, target) => number | bigint | undefined;
```

Return the 1-based position of the first element that is structurally
the same as `target` (the `isSame()` comparison), without a walk of the
collection. `IndexOf(xs, v)` reads it.

Return `0` when no element is the same as `target`, and `undefined` when
the position cannot be computed without a walk. A position that is not a
safe integer is returned as a `bigint`. The answer must be the one a walk
that compares each element with `isSame()` gives.

</MemberCard>

<MemberCard>

### CollectionHandlers {#collectionhandlers}

```ts
type CollectionHandlers = BaseCollectionHandlers & Partial<IndexedCollectionHandlers>;
```

The collection handlers are the primitive operations that can be
performed on collections, such as lists, sets, tuples, etc...

</MemberCard>

### ArithmeticContext {#arithmeticcontext}

The context passed to the hooks of an [ArithmeticDefinition](#arithmeticdefinition).

<MemberCard>

##### ArithmeticContext.engine {#engine-1}

```ts
readonly engine: ComputeEngine;
```

</MemberCard>

<MemberCard>

##### ArithmeticContext.numericApproximation {#numericapproximation}

```ts
readonly numericApproximation: boolean;
```

`true` under `.N()`. The hook numericizes its own result: a kind whose
values are exact (a residue class) computes the exact value anyway; a
kind whose values carry a float (a measurement, an interval) returns the
numeric form. The caller does not apply `.N()` to the result.

</MemberCard>

<MemberCard>

##### ArithmeticContext.tolerance? {#tolerance-1}

```ts
readonly tolerance?: number;
```

For the `compare` hook only: the tolerance of the caller, when it
compares within a tolerance. `.is()` gives the `tolerance` argument of
the call, or `engine.tolerance` when the call has none (`.is()` is the
comparison within a tolerance, also for two exact values). `undefined`
for every other comparison (the relational operators, `isEqual()`,
`isLess()`, `Max`, `Min`, `Sort`, …): the hook then applies its own
rule, usually two exact values compared exactly and a float within
`engine.tolerance`.

</MemberCard>

### KindOperands {#kindoperands}

The operands of an `add`, `multiply` or `apply` hook of an
[ArithmeticDefinition](#arithmeticdefinition).

<MemberCard>

##### KindOperands.evaluated {#evaluated}

```ts
readonly evaluated: readonly Expression[];
```

The evaluated operands.

</MemberCard>

<MemberCard>

##### KindOperands.written {#written}

```ts
readonly written: readonly (Expression | undefined)[];
```

The operands as they were written before evaluation, aligned with
`evaluated`. `undefined` for a value that an earlier fold made, which
has no written form. A kind whose rule depends on how a term was
written reads it here (a temperature with an offset reads `Negate(b)` in
`a - b`).

</MemberCard>

<MemberCard>

##### KindOperands.exact() {#exact}

```ts
exact(i): Expression
```

The exact value of operand `i`: `evaluated[i]` outside `.N()`. Under
`.N()`, the operand evaluated again without the numeric approximation
when it is transitively pure (evaluating it again cannot repeat a side
effect), else `evaluated[i]`. The result is memoized.

####### i

`number`

</MemberCard>

<MemberCard>

##### KindOperands.elements() {#elements}

```ts
elements(i): readonly Expression[] | undefined
```

At an operator whose parameter is a collection type, the elements of
collection operand `i`, enumerated once by the engine. `undefined` for an
operand that is not a collection, or that was not enumerated (a
collection larger than `engine.maxCollectionSize`, of unknown or
infinite count, or whose element type cannot hold a value of a kind).

####### i

`number`

</MemberCard>

<MemberCard>

### KindOperand {#kindoperand}

```ts
type KindOperand = {
  evaluated: Expression;
  written: Expression | undefined;
  exact: Expression;
};
```

One operand of a `negate`, `divide`, `power` or `compare` hook of an
[ArithmeticDefinition](#arithmeticdefinition). The fields have the meaning of the fields of
[KindOperands](#kindoperands) with the same name.

</MemberCard>

### KindFold {#kindfold}

The result of an `add` or `multiply` hook of an
[ArithmeticDefinition](#arithmeticdefinition): the operands that the hook combined, by their
index in `ops.evaluated`, and the value they make.

<MemberCard>

##### KindFold.value {#value-3}

```ts
readonly value: Expression;
```

</MemberCard>

<MemberCard>

##### KindFold.operands {#operands}

```ts
readonly operands: readonly number[];
```

</MemberCard>

### ArithmeticDefinition {#arithmeticdefinition}

The arithmetic of a VALUE KIND, given by the `arithmetic` field of the
operator definition of the head that constructs its values.

The fields marked PER TYPE belong to the kind type (the result type of the
head), because a symbol of that type has no head to ask: `admittedAs`,
`resultType` and `compile.type`. The other fields belong to the head.

Rules for a hook:
- The operands of `add` and `multiply` arrive in canonical order, and
  `multiply` must commute.
- A hook may build and evaluate expressions through the engine, including
  expressions with values of another kind. A hook never calls
  `.simplify()`.
- A hook that throws propagates the error, as an `evaluate` handler does.
- A fold that names an operand index out of range or twice is an error in
  the definition of the kind and throws.

<MemberCard>

##### ArithmeticDefinition.admittedAs? {#admittedas}

```ts
admittedAs?: "number" | "real" | "none";
```

PER TYPE. Where a value of this kind is admitted beyond the arithmetic
operators and the parameters that name its type or admit `value`.
Default `'none'`.

</MemberCard>

<MemberCard>

##### ArithmeticDefinition.add()? {#add-1}

```ts
add(ops, context): readonly KindFold[] | undefined
```

The sum of the operands of which at least one is a value of this kind.
`ops` are the evaluated operands. A fold names the operands it combined,
by their index in `ops.evaluated`, and the value they make. A hook may
return several folds and must not name an operand twice. A fold may name
an operand of another kind only to absorb it into its own value. A
fold's `value` may be a value of another kind or a plain number.
`undefined`, or an empty list, folds nothing.

####### ops

[`KindOperands`](#kindoperands)

####### context

[`ArithmeticContext`](#arithmeticcontext)

</MemberCard>

<MemberCard>

##### ArithmeticDefinition.multiply()? {#multiply}

```ts
multiply(ops, context): readonly KindFold[] | undefined
```

The product of the operands of which at least one is a value of this
kind. The contract is the one of `add`.

####### ops

[`KindOperands`](#kindoperands)

####### context

[`ArithmeticContext`](#arithmeticcontext)

</MemberCard>

<MemberCard>

##### ArithmeticDefinition.negate()? {#negate}

```ts
negate(x, context): Expression | undefined
```

`-x`. `undefined` declines.

####### x

[`KindOperand`](#kindoperand)

####### context

[`ArithmeticContext`](#arithmeticcontext)

</MemberCard>

<MemberCard>

##### ArithmeticDefinition.divide()? {#divide}

```ts
divide(a, b, context): Expression | undefined
```

`a / b`, at least one operand of this kind. `undefined` declines.

####### a

[`KindOperand`](#kindoperand)

####### b

[`KindOperand`](#kindoperand)

####### context

[`ArithmeticContext`](#arithmeticcontext)

</MemberCard>

<MemberCard>

##### ArithmeticDefinition.power()? {#power}

```ts
power(base, exponent, context): Expression | undefined
```

`base ^ exponent`, at least one operand of this kind. `Sqrt(x)` calls it
with the exponent `1/2`, `Root(x, n)` with `1/n`, `Square(x)` with `2`.
`undefined` declines.

####### base

[`KindOperand`](#kindoperand)

####### exponent

[`KindOperand`](#kindoperand)

####### context

[`ArithmeticContext`](#arithmeticcontext)

</MemberCard>

<MemberCard>

##### ArithmeticDefinition.compare()? {#compare}

```ts
compare(a, b, context): 0 | 1 | -1 | "<=" | ">=" | "unordered" | undefined
```

The order of two values of which at least one is of this kind, for the
comparison operators, `Max`, `Min`, `ElementMax`, `ElementMin`, `Sort`,
`Clamp` and the comparison methods:

- `-1`, `0` or `1`: the order of the two values;
- `'unordered'`: the two values are known and have no order (a value
  with a complex or `NaN` nominal). The four order operators (`Less`,
  `LessEqual`, `Greater`, `GreaterEqual`) answer `False`, as they do for
  a complex number; `Equal` and `NotEqual` ask the `eq` handler of the
  head definitions; `Max`, `Min` and `Sort` leave the call unevaluated;
- `'<='`: `a` is less than or equal to `b`, and the hook cannot say
  which (two enclosures that touch: `Enclosure(0, 1)` and
  `Enclosure(1, 2)`). `LessEqual` answers `True` and `Greater` answers
  `False`; `Less` and `GreaterEqual` stay unevaluated; `Equal` and
  `NotEqual` ask the `eq` handlers. `'>='` is the mirror answer. A
  reader that needs a total order (`Sort`, `Max` and `Min` without an
  `extremum` hook) reads them as `undefined`;
- `undefined`: the two values are not comparable (a value of another
  kind, a symbol with no value). An order comparison stays unevaluated,
  `Equal` and `NotEqual` ask the `eq` handlers.

A kind without `compare` has no order.

####### a

[`KindOperand`](#kindoperand)

####### b

[`KindOperand`](#kindoperand)

####### context

[`ArithmeticContext`](#arithmeticcontext)

</MemberCard>

<MemberCard>

##### ArithmeticDefinition.extremum()? {#extremum}

```ts
extremum(which, ops, context): Expression | undefined
```

The maximum (`which` is `'max'`) or the minimum of the operands, of
which at least one is a value of this kind, for `Max`, `Min`,
`ElementMax`, `ElementMin` and `Clamp`. The engine asks this hook
before it orders the operands with `compare`, so a kind whose values
can overlap gives a value that is not one of the operands: the maximum
of two enclosures is the enclosure of the larger ends
(`Max(Enclosure(0, 2), Enclosure(1, 3))` is `Enclosure(1, 3)`).
`undefined` declines, and the engine orders the operands with
`compare`. Absent: the engine orders the operands with `compare`.

####### which

`"max"` \| `"min"`

####### ops

[`KindOperands`](#kindoperands)

####### context

[`ArithmeticContext`](#arithmeticcontext)

</MemberCard>

<MemberCard>

##### ArithmeticDefinition.~~isExact()?~~ {#isexact-1}

```ts
isExact(value): boolean
```

Whether the value `value` of this kind is exact. Absent: a value
of the kind is exact. A measurement is never exact.

The engine does not read this hook now. It is kept for compatibility
with kind definitions that declare it.

####### value

[`Expression`](#expression-5)

###### Deprecated

The engine does not read it: an exact form with no value
gives `NaN`, whether its operands are exact or not.

</MemberCard>

<MemberCard>

##### ArithmeticDefinition.isNaN()? {#isnan-1}

```ts
isNaN(value): boolean
```

Whether the value `value` of this kind stands for no value, as the
number `NaN` does: a measurement with a `NaN` nominal, a quantity with a
`NaN` magnitude. Such a value follows the rule of `NaN` at `Max`, `Min`,
`ElementMax`, `ElementMin` and `Clamp`: `Max(Quantity(NaN, m), 2 m)` is
`NaN`, as `Max(NaN, 2)` is. Absent: no value of the kind is `NaN`.

####### value

[`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### ArithmeticDefinition.numericValue()? {#numericvalue}

```ts
numericValue(value): Expression | undefined
```

The number that the value `value` of this kind stands for, when the
values of the kind stand for a number: the nominal of a measurement.
The numeric accessors of the value read it: `re`, `im`, `bignumRe`,
`bignumIm` and `valueOf()` (`Measurement(2.5, 0.1).re` is `2.5`, and a
complex nominal gives its real and imaginary parts). Absent, or
`undefined`: those accessors answer as for any other expression that
is not a number (`re` is `NaN`).

The FACT queries (`isPositive`, `sgn`, `isInteger`, `isFinite`, …) do
not read it: they stay `undefined` for a value of a kind, so that no
canonical fold of the numbers applies to it.

####### value

[`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### ArithmeticDefinition.apply()? {#apply}

```ts
apply(operator, ops, context): Expression | undefined
```

Called in place of the `evaluate` handler of `operator` when at least one
operand is a value of this kind that the operator admitted only because
of `admittedAs`. `undefined` leaves the expression unevaluated.

####### operator

`string`

####### ops

[`KindOperands`](#kindoperands)

####### context

[`ArithmeticContext`](#arithmeticcontext)

</MemberCard>

<MemberCard>

##### ArithmeticDefinition.resultType()? {#resulttype}

```ts
resultType(operator, operandTypes): 
  | string
  | RecordType
  | AlgebraicType
  | NegationType
  | CollectionType
  | ListType
  | SetType
  | BroadcastableType
  | ObjectType
  | ArrayType
  | DictionaryType
  | TupleType
  | SymbolType
  | ExpressionType
  | NumericType
  | FunctionSignature
  | ValueType
  | TypeVariable
  | TypeReference
  | undefined
```

PER TYPE. The static result type of a cell of `operator` with an operand
of this kind's type, from the operand types without their shapes, or
`undefined` for the default. `operator` is the dispatched operator:
`'Add'` for a sum or a difference, `'Power'` for `Sqrt`, `Root` and
`Square`, with the type of the implied exponent among `operandTypes`.
A type string is parsed in the engine (`'number | uq'`).

####### operator

`string`

####### operandTypes

readonly [`Type`](#type-3)[]

</MemberCard>

<MemberCard>

### TaggedValueDefinition {#taggedvaluedefinition}

```ts
type TaggedValueDefinition = {
  value: BoxedValueDefinition;
};
```

The definition for a value, represented as a tagged object literal.

</MemberCard>

<MemberCard>

### TaggedOperatorDefinition {#taggedoperatordefinition}

```ts
type TaggedOperatorDefinition = {
  operator: BoxedOperatorDefinition;
};
```

The definition for an operator, represented as a tagged object literal.

</MemberCard>

<MemberCard>

### BoxedDefinition {#boxeddefinition}

```ts
type BoxedDefinition = 
  | TaggedValueDefinition
  | TaggedOperatorDefinition;
```

A definition can be either a value or an operator.

It is collected in a tagged object literal, instead of being a simple union
type, so that the type of the definition can be changed while keeping
references to the definition in bound expressions.

</MemberCard>

<MemberCard>

### TypeProvenanceEntry {#typeprovenanceentry}

```ts
type TypeProvenanceEntry = {
  type: BoxedType;
  kind: "declared" | "auto-declared" | "inferred" | "value-derived";
  axis: "type" | "effects";
  cause: Expression;
  span: {
     start: number;
     end: number;
    };
};
```

One recorded write to a definition's type (or an operator definition's
signature): the type the write installed, the mechanism that installed it,
and — for writes triggered by canonicalizing an expression — that
expression.

Provenance can never live on `Type`/`BoxedType` objects themselves: parsed
types are interned, deep-frozen, and shared across engines (the
`TYPE_CACHE` in `common/type/parse.ts`), so two occurrences of `boolean`
are the same object. The history therefore lives on the per-engine
definition, next to `inferredType`.

Design: `docs/TYPE-SYSTEM.md`, phase 1.

</MemberCard>

### BoxedBaseDefinition {#boxedbasedefinition}

#### Extends

- `Partial`\<[`BaseDefinition`](#basedefinition)\>

#### Extended by

- [`BoxedValueDefinition`](#boxedvaluedefinition)
- [`BoxedOperatorDefinition`](#boxedoperatordefinition)

<MemberCard>

##### BoxedBaseDefinition.examples? {#examples-1}

```ts
examples?: string[];
```

The usage examples of the definition. A definition may give a single
string; the boxed definition always stores a list.

</MemberCard>

<MemberCard>

##### BoxedBaseDefinition.collection? {#collection-1}

```ts
collection?: CollectionHandlers;
```

If this is the definition of a collection, the set of primitive operations
that can be performed on this collection (counting the number of elements,
enumerating it, etc...).

</MemberCard>

### BoxedValueDefinition {#boxedvaluedefinition}

#### Extends

- [`BoxedBaseDefinition`](#boxedbasedefinition)

<MemberCard>

##### BoxedValueDefinition.holdUntil {#holduntil}

```ts
holdUntil: "never" | "evaluate" | "N";
```

If the symbol has a value, it is held as indicated in the table below.
A green checkmark indicate that the symbol is substituted.

<div className="symbols-table">

| Operation     | `"never"` | `"evaluate"` | `"N"` |
| :---          | :-----:   | :----:      | :---:  |
| `canonical()` |    (X)    |              |       |
| `evaluate()`  |    (X)    |     (X)      |       |
| `"N()"`       |    (X)    |     (X)      |  (X)  |

</div>

Some examples:
- `ImaginaryUnit` has `holdUntil: 'never'`: it is substituted during canonicalization
- `x` has `holdUntil: 'evaluate'` (variables)
- `Pi` has `holdUntil: 'N'` (special numeric constant)

**Default:** `evaluate`

</MemberCard>

<MemberCard>

##### BoxedValueDefinition.macro? {#macro}

```ts
readonly macro?: MathJsonExpression;
```

The raw body of a macro definition (`ce.declare(name, { macro })`),
`undefined` for every other value definition. A macro definition has no
value and the type `unknown`.

</MemberCard>

<MemberCard>

##### BoxedValueDefinition.value {#value-5}

```ts
value: Expression | undefined;
```

The current value of the symbol: the value an `assume(x = …)` puts in
 force for the current context if there is one, else the stored value.
 For constants, this is immutable.

</MemberCard>

<MemberCard>

##### BoxedValueDefinition.isSelfReferential {#isselfreferential}

```ts
readonly isSelfReferential: boolean;
```

True if the current value refers to the symbol itself (a degenerate
self-referential binding, e.g. `a := a + 1` over an unbound `a`). Such a
binding forms a cycle: resolving the value would re-resolve the symbol
forever. When set, the symbol is treated as unbound during resolution so
that `evaluate()`/`.N()`/collection queries stay symbolic instead of
overflowing the stack. Computed once when the value is assigned.

</MemberCard>

<MemberCard>

##### BoxedValueDefinition.eq? {#eq-1}

```ts
eq?: (a) => boolean | undefined;
```

</MemberCard>

<MemberCard>

##### BoxedValueDefinition.neq? {#neq}

```ts
neq?: (a) => boolean | undefined;
```

</MemberCard>

<MemberCard>

##### BoxedValueDefinition.cmp? {#cmp}

```ts
cmp?: (a) => "<" | ">" | "=" | undefined;
```

</MemberCard>

<MemberCard>

##### BoxedValueDefinition.inferredType {#inferredtype}

```ts
inferredType: boolean;
```

True if the type has been inferred. An inferred type can be updated as
more information becomes available.

A type that is not inferred, but has been set explicitly, cannot be updated.

</MemberCard>

<MemberCard>

##### BoxedValueDefinition.\_programVariable {#_programvariable}

```ts
_programVariable: boolean;
```

</MemberCard>

<MemberCard>

##### BoxedValueDefinition.effectsDeclared {#effectsdeclared}

```ts
effectsDeclared: boolean;
```

Annotation provenance on the EFFECTS axis — the effects-axis analog of
[inferredType](#inferredtype) (`docs/EFFECTS-MODEL.md`, "Annotation provenance").

True when the declaration STATED the arrow's effects (a non-empty
specifier, or the `pure` keyword). False for a bare arrow, which leaves
effects on the inferred track: an assigned body's inferred effects are
accepted and re-stamped, never checked against the declaration.

</MemberCard>

<MemberCard>

##### BoxedValueDefinition.type {#type-6}

```ts
type: BoxedType;
```

The static type of the definition. Assigning it writes its contract.

</MemberCard>

<MemberCard>

##### BoxedValueDefinition.subscriptEvaluate? {#subscriptevaluate-1}

```ts
subscriptEvaluate?: (subscript, options) => Expression | undefined;
```

Custom evaluation handler for subscripted expressions of this symbol.
Called when evaluating `Subscript(symbol, index)`.

</MemberCard>

<MemberCard>

##### BoxedValueDefinition.dispose() {#dispose}

```ts
dispose(): void
```

Release resources owned by this definition when its scope is disposed.

</MemberCard>

<MemberCard>

### BroadcastExemption {#broadcastexemption}

```ts
type BroadcastExemption = 
  | "tensors"
  | "tuples"
  | "collection-result"
  | "evaluated-operands"
  | "whole-collection-compare"
  | "single-collection-join"
  | "surplus-operands";
```

A shape of operand (or result) whose broadcast handling an operator's own
handlers provide, exempting it from the generic broadcast machinery. See
[OperatorDefinitionFlags.broadcastExemptions](#operatordefinitionflags) for the meaning of
each label.

</MemberCard>

<MemberCard>

### OperandRole {#operandrole}

```ts
type OperandRole = 
  | {
  kind: "value";
 }
  | {
  kind: "held";
 }
  | {
  kind: "statement";
 }
  | {
  kind: "raw";
 }
  | {
  kind: "opaque";
 }
  | {
  kind: "bound";
  type: TypeString;
 }
  | {
  kind: "clause";
  type: TypeString;
  unordered: boolean;
};
```

The role of one operand of an operator, as the `operands` handler of
[OperatorDefinitionFlags](#operatordefinitionflags) declares it. The role says how the operand
is canonicalized and whether it is evaluated before the `evaluate` handler
of the operator runs.

- `value`: the operand is a value, and an `Assign` or a `Declare` there is
  an error. In an operator that is not `lazy`, the operand is
  canonicalized, checked against the signature, and evaluated before the
  `evaluate` handler runs; this is the default role of such an operator.
  In a `lazy` operator, the handlers receive the operand as written and
  canonicalize and evaluate it themselves; only a bare `N` or `D` there is
  read as a variable, not as the library operator.
- `held`: the operand is a value that the `evaluate` handler receives as
  its canonicalization left it, not evaluated, so that the handler can
  read it as written (`Fibonacci(10^6)` in `Mod(Fibonacci(10^6), p)`) and
  evaluate it itself when it needs its value. Otherwise the operand is a
  `value`: it is canonicalized and checked against the signature, the
  type and the validity of the application read it, an `Assign` or a
  `Declare` there is an error, and a literal list there is broadcast, each
  element held. An operand that only its evaluation makes a list is held
  whole. Valid only on an operator that is not `lazy`: a `lazy` operator
  canonicalizes none of its operands, and its handlers receive every
  operand unevaluated (`raw`).
- `statement`: the operand is a statement that the operator runs, zero,
  one or several times (the body of a loop, a branch of a conditional). An
  `Assign` there is valid. The operand is not evaluated
  before the `evaluate` handler runs: the handler evaluates it when and as
  often as it needs to. The engine canonicalizes the operand as a branch,
  except in a `lazy` operator with a `canonical` handler, which receives
  it as written and canonicalizes it itself. In a branch, a `Declare` is
  the error `declaration-below-statement`, an assignment of a name that
  no enclosing scope declares is the error
  `assignment-to-undeclared-variable`, an assignment of a declared name
  writes that name, and a bare `Break` or `Continue` symbol is an error.
- `raw`: the operand is kept as written, not canonicalized and not
  evaluated. The default of a `lazy` operator. Valid only on a `lazy`
  operator.
- `opaque`: the operand is kept as written, and an `Assign` or a `Declare`
  in it is valid (the expression of `Hold` and of `Error`). Valid only on a
  `lazy` operator.
- `bound`: the operand is a bound variable of the operator, a symbol
  that the operator declares in its own scope (the variable of `D(f, x)`,
  the expansion variable of `Series`), with the type `type` (`unknown`
  when it is left out). A symbol held in a `Hold` is a bound variable
  too; any other operand declares nothing. The variable remains a free
  variable of the expression, as for `D`: the value of `D(x^2, x)` is a
  function of `x`. The operand is not evaluated before the `evaluate`
  handler runs; it is kept as written in a `lazy` operator, and
  canonicalized in the scope of the operator otherwise.
- `clause`: the operand is an indexing set whose index is a bound
  variable of the operator: `Limits(k, 1, 10)`, `Element(k, S)` (a
  tuple pattern `Element(Tuple(p, q), S)` binds each of its names), a
  tuple `Tuple(k, 1, 10)` or `Triple(k, 1, 10)`, a set `Set(k, 1, 10)`,
  a parenthesized tuple of the LaTeX parser, or a symbol, also held.
  `type` is the type of the index of a range-shaped clause. When `type`
  is `integer` and the bounds are integer literals, the index has the
  ranged type (`integer<1..10>` for `Limits(k, 1, 10)`); any other
  `type` is used as given. The index of an `Element` clause does not
  take `type`: it is `integer<a..b>` for a range `Range(a, b)` with
  integer literal bounds, and otherwise an inferred `unknown` that a
  `canonical` handler can narrow from the collection. The index is not a
  free variable of the expression. It is visible in its own clause, in
  the later clauses and in the operands before the first clause (the
  body), not in an earlier clause. With `unordered: true`, it is visible
  in the earlier clauses of the run of consecutive `clause` operands too,
  for an operator that evaluates its clauses in the order of their
  dependencies, not in the written order: `Sum` and `Product`, where
  `Sum(i·j, Element(j, Range(1, i)), Limits(i, 1, 3))` is the sum over
  `i` of the sum over `j`. Consecutive `clause` operands are read as the clauses of
  `Sum`, with the flat spelling: in `Sum(body, k, 1, 10)` the operands
  after the symbol `k` are its bounds, not indexes. An operand that holds
  no index declares nothing. The operand is not evaluated before the
  `evaluate` handler runs, and is canonicalized as a `bound` operand is.

An operator whose `operands` handler gives a `bound` or a `clause` role
is a **binder**: it has its own scope, as with `scoped: true`, and the
engine declares each bound variable in that scope before it canonicalizes
the other operands, so that the parse, `ce.box()` and `ce.function()`
routes bind the same variable. The engine finds that the operator is a
binder when it is declared (see the `operands` handler of
[OperatorDefinitionFlags](#operatordefinitionflags)).

</MemberCard>

<MemberCard>

### OperatorDefinitionFlags {#operatordefinitionflags}

```ts
type OperatorDefinitionFlags = {
  lazy: boolean;
  operands: (ops) => ReadonlyArray<OperandRole>;
  scoped: boolean;
  broadcastable: boolean;
  broadcastExemptions: ReadonlyArray<BroadcastExemption>;
  threadsConditionals: boolean | number[];
  inspectsErrors: boolean;
  selectsOperands: boolean;
  evaluatesOperands: boolean;
  namedArgumentsRequired: boolean;
  missingBehavior: "reject" | "propagate" | "handle";
  missingStrip: "all" | number[];
  nanBehavior:   | "reject"
     | "propagate"
     | "handle"
     | ReadonlyArray<"reject" | "propagate" | "handle" | undefined>;
  partiality: "total" | "may-marker";
  definedWhen: (ops) => boolean | undefined;
  requires: (ops) => boolean | undefined;
  associative: boolean;
  commutative: boolean;
  commutativeOrder: ((a, b) => number) | undefined;
  commutativeMatch: boolean;
  idempotent: boolean;
  involution: boolean;
  pure: boolean;
  effects: EffectSet | undefined;
  effectsDeclared: boolean;
  frameProtocol: "seed" | undefined;
  invokes: boolean | {};
  discharges: {} | undefined;
  holdClass: "evaluate" | "quote" | "release";
  drawsRandom: boolean;
  readsRandomFrame: boolean;
};
```

An operator definition can have some flags to indicate specific
properties of the operator.

</MemberCard>

<MemberCard>

### LambdaDefinition {#lambdadefinition}

```ts
type LambdaDefinition = {
  parameters: ReadonlyArray<{
     name: string;
     type: Type | undefined;
     optional: boolean;
     default: ParameterDefault;
    }>;
  body: Expression;
};
```

A traversable, public view of a user-defined function literal
(`f(x) := …`, `x ↦ …`, or `ce.assign('f', lambda)`): its parameters and
its body as a boxed expression. Returned by
[BoxedOperatorDefinition.lambda](#lambda).

</MemberCard>

### BoxedOperatorDefinition {#boxedoperatordefinition}

The definition includes information specific about an operator, such as
handlers to canonicalize or evaluate a function expression with this
operator.

#### Extends

- [`BoxedBaseDefinition`](#boxedbasedefinition)
- [`OperatorDefinitionFlags`](#operatordefinitionflags)

<MemberCard>

##### BoxedOperatorDefinition.parameters? {#parameters-1}

```ts
parameters?: 
  | Readonly<Record<string, ParameterDocumentation>>
  | readonly ParameterDocumentation[];
```

The documentation of the parameters, keyed by parameter name or by
position (`OperatorDefinition.parameters`).

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.scoped {#scoped-1}

```ts
scoped: boolean;
```

`true` when the operator creates a lexical scope: it was declared
`scoped: true`, or it is a binder, whose `operands` handler gives a
`bound` or a `clause` role.

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.complexity {#complexity}

```ts
complexity: number;
```

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.inferredSignature {#inferredsignature}

```ts
inferredSignature: boolean;
```

If true, the signature was inferred from usage and may be modified
as more information becomes available.

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.signature {#signature}

```ts
signature: BoxedType;
```

The type of the arguments and return value of this function

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.resolvedMissingBehavior {#resolvedmissingbehavior}

```ts
readonly resolvedMissingBehavior: "reject" | "propagate" | "handle" | "pass-through";
```

The *resolved* missing-value behavior (§3.A of the missing-value typing
design): the declared `missingBehavior` flag of [OperatorDefinitionFlags](#operatordefinitionflags)
when present, otherwise
`'propagate'` for a declared all-numeric signature and `'pass-through'`
for everything else. Recomputed from the current signature — never cached
across a signature mutation.

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.enforcesParameterAnnotations {#enforcesparameterannotations}

```ts
readonly enforcesParameterAnnotations: boolean;
```

True for a function literal whose parameter annotations are enforced at
a call (at least one annotated parameter). Such a function admits an
argument typed `missing | T` at boxing, and answers an
`incompatible-type` error when the value is absent at a parameter whose
annotation has no `missing` member.

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.resolvedPartiality {#resolvedpartiality}

```ts
readonly resolvedPartiality: "total" | "may-marker" | "defined-when";
```

The *resolved* partiality of the declaration (Contract B): the
declared `partiality`, `'defined-when'` when a `definedWhen` predicate
is declared, and the sound `'may-marker'` default when nothing is.

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.isUserFunctionDefinition {#isuserfunctiondefinition}

```ts
readonly isUserFunctionDefinition: boolean;
```

True for a USER-DEFINED callable — a lambda, or an unscoped strict
multi-clause definition. The sanctioned opt-out of the Contract B
machinery: its own application machinery owns every exceptional
operand, and the higher-order conservative floor
(`docs/ERROR-MODEL.md` §4) caps what a consumer may assume about it
at `may-marker` with unknown NaN behavior.

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.invokesNone {#invokesnone}

```ts
readonly invokesNone: boolean;
```

True when NO operand position invokes — the cheap operator-level
pre-gate for the latent half of the projection rule.

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.lambda {#lambda}

```ts
readonly lambda: LambdaDefinition | undefined;
```

If this operator definition was created from a user-defined function
literal (`f(x) := …`, `x ↦ …`, `ce.assign('f', lambda)`), a structured
view of it for traversal and classification: the parameters and the body
as a boxed expression. `undefined` for built-in operators.

The return shape and per-argument types are also available via
[signature](#signature); this accessor additionally exposes the body so a
consumer can resolve a function reference structurally — without
re-parsing or textually inlining its source.

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.type? {#type-7}

```ts
type?: OperatorTypeHandlerOnTypes;
```

If present, this handler determines the result type more precisely
than the signature, from the operand DESCRIPTORS (types, facts and
structure — never the operand expressions).

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.sgn? {#sgn-2}

```ts
sgn?: (ops, options) => Sign | undefined;
```

If present, this handler can be used to determine the sign of the
 return value of the function, based on the sign and type of its
 arguments.

The arguments themselves should *not* be evaluated, only their types and
sign should be used.

This can be used in some case for example to determine when certain
simplifications are valid.

The handler MUST be a pure function of the operands: no evaluation
(`.evaluate()`, `.N()` — including indirectly, through helpers that
numericize a bound or probe a collection element), no canonicalization
of new expressions, no declarations. The type path dispatches `sgn`
handlers while deriving an application's type (the `sgn` operand fact),
so a handler that changes engine state invalidates the very caches the
derivation is filling. Audit record: open item O7 of
`docs/plans/2026-08-22-type-handlers-on-types.md`.

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.eq? {#eq-2}

```ts
eq?: (a, b, prover?) => boolean | undefined;
```

See `OperatorDefinition.eq` for the meaning of `prover`.

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.neq? {#neq-1}

```ts
neq?: (a, b) => boolean | undefined;
```

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.canEnumerate? {#canenumerate}

```ts
canEnumerate?: (expr) => boolean | undefined;
```

The eager producer's enumerability precondition — see the
`canEnumerate` contract on [OperatorDefinition](#operatordefinition).

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.elementCount? {#elementcount}

```ts
elementCount?: (expr) => number | undefined;
```

The eager producer's element count — see the `elementCount` contract on
[OperatorDefinition](#operatordefinition).

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.elementAt? {#elementat}

```ts
elementAt?: (expr, index) => Expression | undefined;
```

The eager producer's element read — see the `elementAt` contract on
[OperatorDefinition](#operatordefinition).

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.inferOperandTypes? {#inferoperandtypes}

```ts
inferOperandTypes?: (ops, requirement) => 
  | readonly (
  | Type
  | {
  replace: Type;
 }
  | undefined)[]
  | undefined;
```

Use-driven element inference — see the `inferOperandTypes` contract on
[OperatorDefinition](#operatordefinition).

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.canonical? {#canonical}

```ts
canonical?: (ops, options) => Expression | null;
```

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.evaluate? {#evaluate}

```ts
evaluate?: (ops, options) => Expression | undefined;
```

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.evaluateAsync? {#evaluateasync}

```ts
evaluateAsync?: (ops, options) => Promise<Expression | undefined>;
```

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.evaluateMod? {#evaluatemod}

```ts
evaluateMod?: EvaluateModHandler;
```

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.evalDimension? {#evaldimension}

```ts
evalDimension?: (ops, options) => Expression;
```

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.derivative? {#derivative}

```ts
derivative?: OperatorDerivative;
```

The partial derivatives of the operator, as given by the `derivative`
key of its definition. See [OperatorDerivative](#operatorderivative).

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.compile? {#compile}

```ts
compile?: OperatorCompileHandler;
```

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.arithmetic? {#arithmetic}

```ts
arithmetic?: ArithmeticDefinition;
```

The arithmetic of the value kind this operator constructs, as given by
the `arithmetic` field of its definition. See
[ArithmeticDefinition](#arithmeticdefinition).

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.stripsMissingAt() {#stripsmissingat}

```ts
stripsMissingAt(i): boolean
```

True if a `missing` arm is stripped from parameter position `i` before
validation (§3.A). Only `propagate`/`handle` operators strip; `missingStrip`
selects the positions.

####### i

`number`

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.declaredParameterTypeAt() {#declaredparametertypeat}

```ts
declaredParameterTypeAt(i): Type | undefined
```

The declared type of parameter position `i` (0-based: the required
parameters, then the optional ones, then the variadic one for every
later position), or `undefined` for an overload set or a position past a
non-variadic signature.

####### i

`number`

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.refusesAbsentOperandAt() {#refusesabsentoperandat}

```ts
refusesAbsentOperandAt(i): boolean
```

True when an absent scalar operand (`Missing`) at position
`i` is refused at evaluation with an `incompatible-type` error naming the
parameter's type: a declared `reject`, or the default for an operator
with no absence behavior of its own whose parameter at `i` excludes
absence and is read as data (not a number, a collection, a function,
`expression`, `symbol`, `any` or `unknown`). User decision P2 of
`docs/plans/2026-10-21-presence-contracts-and-assertion.md`
(2026-10-21).

####### i

`number`

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.threadsConditionalsAt() {#threadsconditionalsat}

```ts
threadsConditionalsAt(i): boolean
```

True if the `threadsConditionals` flag of
[OperatorDefinitionFlags](#operatordefinitionflags) selects operand position `i`: a
conditional value (a restriction, `Which`) there moves out of the application at
evaluation. A broadcastable operator threads every position whatever this
answers.

####### i

`number`

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.operandRoles() {#operandroles}

```ts
operandRoles(ops): 
  | readonly ("value" | "raw" | "opaque" | "held" | "statement" | "bound" | "clause")[]
  | undefined
```

The kind of the role of each operand of `ops`, the operands of an
application of this operator, as the `operands` handler of
[OperatorDefinitionFlags](#operatordefinitionflags) declares them, with the default role
(`value`, or `raw` for a `lazy` operator) for a position that the
handler leaves out. One entry per operand. `undefined` when the
definition has no `operands` handler: every operand then has the
default role.

####### ops

readonly [`Expression`](#expression-5)[]

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.resolvedNanBehaviorAt() {#resolvednanbehaviorat}

```ts
resolvedNanBehaviorAt(i, armSignature?): "reject" | "propagate" | "handle" | "inert"
```

The *resolved* NaN policy for parameter position `i` (Contract B,
`docs/ERROR-MODEL.md` §4). For a user-defined callable the answer is
always `'inert'` — the higher-order conservative floor, absolute even
over an explicit declaration (see `isUserFunctionDefinition`).
Otherwise an explicit `nanBehavior` declaration wins.
Otherwise, while the slot's declared carrier admits `nan` (bare
`number`, an inferred signature, a union with `nan`) the answer is
`'inert'` — `NaN` is an ordinary domain member and the handler owns
it. For a precise carrier that excludes `nan`, the derived default is
`'propagate'` when the carrier is a subtype of `complex` that is not a
subtype of `integer` and the result type is numeric, `'reject'`
otherwise. Recomputed from the current signature — never cached.

####### i

`number`

####### armSignature?

[`Type`](#type-3)

The resolved overload arm to derive from, when the caller has one:
per-arm carriers give per-arm derived policies. Explicit
`nanBehavior` declarations remain operator-level.

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.contractBResultAdjustment() {#contractbresultadjustment}

```ts
contractBResultAdjustment(ops, armSignature?): 
  | "none"
  | "is-nan"
  | "widen-nan"
  | "widen-nan-cells"
  | "widen-marker"
  | "is-marker"
```

The Contract B adjustment to a derived application result type for
these arguments (`docs/ERROR-MODEL.md` §4): `'is-marker'` when the
declared `definedWhen` is provably false — the value IS the codomain
marker (§2 rule 4: `NaN` for a numeric codomain, `Missing` for a
settled non-numeric one); `'widen-marker'` when a DECLARED partiality
is undischarged (`definedWhen` undecided, or an explicit
`may-marker`) — every cell of the result gains its marker arm;
`'is-nan'` when a scalar argument in a `propagate` slot is a proven
`NaN` — the value of the whole application is `NaN`, whatever the
codomain's shape; `'widen-nan'` when such an argument may be `NaN` —
the application gains a top-level `| nan` arm; `'widen-nan-cells'`
when the NaN evidence rides in the cells of a broadcast lift — the
lifted result's numeric cells gain `| nan`; `'none'` otherwise. The
omitted `may-marker` default contributes no arm (see
the implementation note in `boxed-operator-definition.ts`).

####### ops

readonly [`Expression`](#expression-5)[]

####### armSignature?

[`Type`](#type-3)

The resolved overload arm, when the caller has one — the NaN
evidence derives per-slot policies from its carriers.

</MemberCard>

<MemberCard>

##### BoxedOperatorDefinition.invokesAt() {#invokesat}

```ts
invokesAt(i): boolean
```

True if operand position `i` may INVOKE a function-valued operand — the
per-position reader for the `invokes` flag of [OperatorDefinitionFlags](#operatordefinitionflags).
Missing
map indices default to `true`. Every consumer of the metadata goes
through this accessor (or [invokesNone](#invokesnone)), never the raw field.

####### i

`number`

</MemberCard>

<MemberCard>

### DeclareOptions {#declareoptions}

```ts
type DeclareOptions = {
  scope: Scope;
  extend: boolean;
};
```

The options of `ce.declare(id, def, options)`.

- `scope`: the scope the declaration is installed in. The default is the
  current lexical scope.
- `extend`: when `true`, `def` is a PATCH applied to the operator definition
  currently visible for `id`, not a new definition. See
  [OperatorDefinitionPatch](#operatordefinitionpatch).

</MemberCard>

<MemberCard>

### InferResult {#inferresult}

```ts
type InferResult = {
  declared: {
     name: string;
     scope: Scope;
     type: Type;
    }[];
  skipped: {
     name: string;
     scope: Scope;
     reason: "conflict" | "untyped" | "defined" | "out-of-scope";
    }[];
};
```

The result of `ce.infer()`.

- `declared`: each name that `ce.infer()` declared in its home scope, or
  whose inferred definition it narrowed there, with the type it has now.
- `skipped`: each symbol of the expressions that it did not change, with
  the reason:
  - `'conflict'`: the expressions require types that have no common
    subtype (`x + 1` and `x(3)`), or a type that has none in common with
    the inferred definition of the name;
  - `'untyped'`: no use requires a type of the name (`q` in `[q]`), or the
    requirements give the type `unknown`;
  - `'defined'`: the home scope holds a definition of the name with a
    declared type (`ce.declare('x', 'real')`). A definition with the
    declared type `unknown` states no type: `ce.infer()` gives it the type
    that the uses require;
  - `'out-of-scope'`: the home scope is not the current scope or one of its
    ancestors (it was popped).

A symbol whose type is already the type that the uses require, a symbol
of the library (`Pi`), a parameter of a function literal, the variable of
a binder (the index of a `Sum`) and a symbol declared in a scope that was
popped are in neither list.

Each list is sorted by name, then by the depth of the scope.

</MemberCard>

<MemberCard>

### OperatorDefinitionPatch {#operatordefinitionpatch}

```ts
type OperatorDefinitionPatch = Omit<OperatorDefinition, "compile"> & {
  addSignature:   | Type
     | TypeString;
  compile: "inherit" | OperatorCompileHandler;
};
```

The patch `ce.declare(id, patch, { extend: true })` applies to the operator
definition currently visible for `id`.

The engine builds a NEW definition from the fields of the visible one and
the fields of the patch, and installs it in the target scope. A field the
patch does not name keeps its value. A field the patch names replaces the
old value: when two extensions give the same handler (two `evaluate`
handlers, for example), the later one wins. The visible definition is not
changed, so an expression boxed before the extension keeps using it.

- `signature` replaces the signature.
- `addSignature` adds an overload: the new signature is the intersection
  `old & addSignature`. A call that matches both arms resolves to the old
  arm first.

In both cases the new signature must be a subtype of the old one, so that
every call that was valid stays valid. For example `(value, value*) -> set`
can replace `(set<any>, value*) -> set`, but `(any*) -> any` cannot replace
`(value+) -> value`. This does not apply when the old signature was only
inferred (`inferredSignature` is `true`: an operator declared without a
signature, or a function whose signature is inferred from its body),
since such a signature is not a contract.

Extending a standard-library operator without replacing its `evaluate`,
`canonical`, `compile` or `derivative` handler (for example, to add a
description or a wider signature) keeps it a library operator: `D`,
compilation and the numeric evaluation of the library still apply to it.
An extension that replaces one of these handlers is treated as a user
definition with the same name, as a plain `ce.declare()` is. The `compile`
field of the patch (`'inherit'` or a handler) lets such an extension keep
the library lowering for compilation.

#### OperatorDefinitionPatch.compile?

```ts
compile?: "inherit" | OperatorCompileHandler;
```

How the patch treats the compiled lowering of the operator.

- `'inherit'`: the new `evaluate` agrees with every call that the library
  lowering compiles, so `compile()` lowers the operator as the library
  does, as if `evaluate` had not been replaced.
- a handler ([OperatorCompileHandler](#operatorcompilehandler)): it gets the `compile` of
  the extended definition as `context.inherited`, and the answer
  `undefined` keeps the library lowering of that call.

A patch that replaces `evaluate` and states no `compile` declines to
compile the operator. Only the compiler reads this field: `D` and the
canonical folds treat a definition with another `evaluate` as a user
definition.

</MemberCard>

### EqHandlers {#eqhandlers}

These handlers compare two expressions.

If only one of the handlers is provided, the other is derived from it.

Having both may be useful if comparing non-equality is faster than equality.

<MemberCard>

##### EqHandlers.eq {#eq-3}

```ts
eq: (a, b) => boolean | undefined;
```

</MemberCard>

<MemberCard>

##### EqHandlers.neq {#neq-2}

```ts
neq: (a, b) => boolean | undefined;
```

</MemberCard>

<MemberCard>

### Hold {#hold-2}

```ts
type Hold = "none" | "all" | "first" | "rest" | "last" | "most";
```

</MemberCard>

## Host Capabilities

### ConsoleHandler {#consolehandler}

The host console, as the engine sees it: the implementation behind the
`console` effect label. The `Print` operator calls `log`; the `Input`
operator calls `readLine`.

<MemberCard>

##### ConsoleHandler.log() {#log}

```ts
log(line): void
```

Write one line of text. The line has no trailing newline; the handler
adds the line break its output medium needs.

####### line

`string`

</MemberCard>

<MemberCard>

##### ConsoleHandler.readLine() {#readline}

```ts
readLine(prompt?): string | null | undefined
```

Read one line of text, synchronously. `prompt`, when given, is displayed
before the read.

The three results are distinct:
- a string: the line, without its trailing newline;
- `null`: end of input, or the user canceled the read — `Input`
  evaluates to `Nothing`;
- `undefined`: this host has no interactive input — `Input` stays
  unevaluated.

####### prompt?

`string`

</MemberCard>

### EntropyHandler {#entropyhandler}

The unseeded source of randomness of the host: the implementation behind
the `entropy` effect label. `RandomExpression` draws from it, and so does
every random operator (`Random`, `Shuffle`, `RandomChoice`, …) when it is
evaluated OUTSIDE a `WithRandomSeed` frame — inside a frame the draws come
from the seeded, deterministic stream and this handler is not consulted.

<MemberCard>

##### EntropyHandler.random() {#random}

```ts
random(): number
```

Return a uniformly distributed number in `[0, 1)`.

</MemberCard>

### EffectHandlers {#effecthandlers}

The host capabilities of an engine: one handler for each capability the
library operators can reach. This is the value of `ce.effects`.

A handler is either an implementation or **`null`**. `null` is a denial:
an operator that needs the capability evaluates to an
`Error("capability-denied", …)` value instead of reaching the host.

The object is immutable. To change a handler, install a new registry:
assign `ce.effects`, or call `ce.withEffects()` for a change that lasts for
one callback.

Only `console` and `entropy` have a handler today, because the console
operators and the random operators are the only library operators that
reach a host capability. The other capability labels of the effect system
(`network`, `fs_read`, `fs_write`, `time`, `environment`) get a handler when
the first operator that needs one is added: a handler that no operator
reads would accept an override and silently do nothing.

<MemberCard>

##### EffectHandlers.console {#console}

```ts
readonly console: ConsoleHandler | null;
```

</MemberCard>

<MemberCard>

##### EffectHandlers.entropy {#entropy}

```ts
readonly entropy: EntropyHandler | null;
```

</MemberCard>

<MemberCard>

### EffectHandlerOverrides {#effecthandleroverrides}

```ts
type EffectHandlerOverrides = { readonly [K in keyof EffectHandlers]?: EffectHandlers[K] };
```

A partial change to the host capabilities, for `ce.withEffects()` and the
`ce.effects` setter. For each capability:
- an implementation replaces the current handler;
- `null` denies the capability, even when the default handler exists;
- an absent key, or `undefined`, keeps the current handler.

</MemberCard>

## Latex Parsing and Serialization

<MemberCard>

### LatexToken {#latextoken}

```ts
type LatexToken = string | "<{>" | "<}>" | "<space>" | "<$>" | "<$$>";
```

A `LatexToken` is a token as returned by `Parser.peek`.

It can be one of the indicated tokens, or a string that starts with a
`` for LaTeX commands, or a LaTeX character which includes digits,
letters and punctuation.

</MemberCard>

<MemberCard>

### LatexString {#latexstring}

```ts
type LatexString = string;
```

A LatexString is a regular string of LaTeX, for example:
`\frac{\pi}{2}`

</MemberCard>

<MemberCard>

### Delimiter {#delimiter}

```ts
type Delimiter = 
  | "."
  | ")"
  | "("
  | "]"
  | "["
  | "{"
  | "}"
  | "<"
  | ">"
  | "|"
  | "||"
  | "\\lceil"
  | "\\rceil"
  | "\\lfloor"
  | "\\rfloor"
  | "\\llbracket"
  | "\\rrbracket";
```

Open and close delimiters that can be used with [`MatchfixEntry`](#matchfixentry)
record to define new LaTeX dictionary entries.

</MemberCard>

<MemberCard>

### DelimiterScale {#delimiterscale}

```ts
type DelimiterScale = "normal" | "scaled" | "big" | "none";
```

</MemberCard>

<MemberCard>

### LibraryCategory {#librarycategory}

```ts
type LibraryCategory = 
  | "arithmetic"
  | "calculus"
  | "collections"
  | "colors"
  | "control-structures"
  | "combinatorics"
  | "core"
  | "linear-algebra"
  | "logic"
  | "number-theory"
  | "other"
  | "physics"
  | "polynomials"
  | "relop"
  | "statistics"
  | "trigonometry"
  | "units";
```

</MemberCard>

<MemberCard>

### Precedence {#precedence}

```ts
type Precedence = number;
```

:::info[THEORY OF OPERATIONS]

The precedence of an operator is a number that indicates the order in which
operators are applied.

For example, in `1 + 2 * 3`, the `*` operator has a **higher** precedence
than the `+` operator, so it is applied first.

The precedence ranges from 0 to 1000. The larger the number, the higher the
precedence, the more "binding" the operator is.

### Operator Precedence Table

| Precedence | Operators | Description |
|------------|-----------|-------------|
| **880** | `\lnot` `\neg` `++` `--` `+` `-` (prefix) | Prefix/postfix unary |
| **810** | `!` `'` `!!` `'''` | Factorial, prime (postfix) |
| **800** | `_` (subscript) | Subscript |
| **780** | `\degree` `\prime` | Degree, prime symbols |
| **740** | `\%` | Percent |
| **720** | `/` (inline division) | Inline division |
| **700** | `^` `\overset` `\underset` | Exponentiation, over/underscript |
| **650** | (invisible multiply) `\cdot` | Implicit multiplication |
| **600** | `\div` `\frac` | Division |
| **390** | `\times` `*` `/` | Multiplication |
| **350** | `\cup` `\cap` | Set union/intersection |
| **275** | `+` `-` (infix) | Addition, subtraction |
| **270** | `\to` `\rightarrow` `\mapsto` | Arrows |
| **265** | `\setminus` `\smallsetminus` `:` (range) | Set difference, range |
| **260** | `:=` | Assignment |
| **255** | `\ne` | Not equal |
| **250** | `\not\approxeq` | Not approximately equal |
| **247** | `\approx` | Approximately |
| **245-246** | `=` `<` `>` `\lt` `\gt` `\nless` `\ngtr` | Equality, comparison |
| **241-244** | `\le` `\leq` `\ge` `\geq` `>=` | Less/greater or equal |
| **240** | `\in` `\notin` `\subset` `\supset` ... | Set membership/relations |
| **235** | `\land` `\wedge` `\&` | Logical AND |
| **232** | `\veebar` `\barwedge` (Xor, Nand, Nor) | Logical XOR, NAND, NOR |
| **230** | `\lor` `\vee` `\parallel` | Logical OR |
| **220** | `\implies` `\Rightarrow` `\vdash` `\models` | Implication, entailment |
| **219** | `\iff` `\Leftrightarrow` `\equiv` | Equivalence |
| **200** | `\forall` `\exists` `\exists!` | Quantifiers |
| **160** | `\mid` `\vert` (set builder) | Set builder notation |
| **19-20** | `,` `;` `\ldots` | Sequence separators |

### Key Relationships

- **Comparisons bind tighter than logic**: `x = 1 \lor y = 2` parses as
  `(x = 1) \lor (y = 2)`, not `x = (1 \lor y) = 2`
- **AND binds tighter than OR**: `a \land b \lor c` parses as
  `(a \land b) \lor c`
- **Logic operators bind tighter than implication**: `a \lor b \implies c`
  parses as `(a \lor b) \implies c`

Some constants are defined below for common precedence values.

**Note**: MathML defines
[some operator precedence](https://www.w3.org/TR/2009/WD-MathML3-20090924/appendixc.html),
but it has some issues and inconsistencies. However,
whenever possible we adopted the MathML precedence.

The JavaScript operator precedence is documented
[here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence).

:::

</MemberCard>

<MemberCard>

### Terminator {#terminator}

```ts
type Terminator = {
  minPrec: Precedence;
  condition: (parser) => boolean;
};
```

This indicates a condition under which parsing should stop:
- an operator of a precedence higher than specified has been encountered
- the last token has been reached
- or if a condition is provided, the condition returns true

</MemberCard>

<MemberCard>

### ParseHandler {#parsehandler}

```ts
type ParseHandler = 
  | ExpressionParseHandler
  | SymbolParseHandler
  | FunctionParseHandler
  | EnvironmentParseHandler
  | PostfixParseHandler
  | InfixParseHandler
  | MatchfixParseHandler;
```

**Custom parsing handler.**

When this handler is invoked the parser points right after the LaTeX
fragment that triggered it.

Tokens can be consumed with `parser.nextToken()` and other parser methods
such as `parser.parseGroup()`, `parser.parseOptionalGroup()`, etc...

If it was in an infix or postfix context, `lhs` will represent the
left-hand side argument. In a prefix or matchfix context, `lhs` is `null`.

In a superfix (`^`) or subfix (`_`) context (that is if the first token of
the trigger is `^` or `_`), `lhs` is `["Superscript", lhs, rhs]`
and `["Subscript", lhs, rhs]`, respectively.

The handler should return `null` if the tokens could not be parsed
(didn't match the syntax that was expected), or the matching expression
otherwise.

If the tokens were parsed but should be ignored, the handler should
return `Nothing`.

</MemberCard>

<MemberCard>

### ExpressionParseHandler {#expressionparsehandler}

```ts
type ExpressionParseHandler = (parser, until?) => MathJsonExpression | null;
```

</MemberCard>

<MemberCard>

### PrefixParseHandler {#prefixparsehandler}

```ts
type PrefixParseHandler = (parser, until?) => MathJsonExpression | null;
```

</MemberCard>

<MemberCard>

### SymbolParseHandler {#symbolparsehandler}

```ts
type SymbolParseHandler = (parser, until?) => MathJsonExpression | null;
```

</MemberCard>

<MemberCard>

### FunctionParseHandler {#functionparsehandler}

```ts
type FunctionParseHandler = (parser, until?) => MathJsonExpression | null;
```

</MemberCard>

<MemberCard>

### EnvironmentParseHandler {#environmentparsehandler}

```ts
type EnvironmentParseHandler = (parser, until?) => MathJsonExpression | null;
```

</MemberCard>

<MemberCard>

### PostfixParseHandler {#postfixparsehandler}

```ts
type PostfixParseHandler = (parser, lhs, until?) => MathJsonExpression | null;
```

</MemberCard>

<MemberCard>

### InfixParseHandler {#infixparsehandler}

```ts
type InfixParseHandler = (parser, lhs, until) => MathJsonExpression | null;
```

</MemberCard>

<MemberCard>

### MatchfixParseHandler {#matchfixparsehandler}

```ts
type MatchfixParseHandler = (parser, body) => MathJsonExpression | null;
```

</MemberCard>

<MemberCard>

### LatexArgumentType {#latexargumenttype}

```ts
type LatexArgumentType = 
  | "{expression}"
  | "[expression]"
  | "{text}"
  | "[text]"
  | "{unit}"
  | "[unit]"
  | "{glue}"
  | "[glue]"
  | "{string}"
  | "[string]"
  | "{color}"
  | "[color]";
```

</MemberCard>

<MemberCard>

### Trigger {#trigger}

```ts
type Trigger = {
  latexTrigger: LatexString | LatexToken[];
  symbolTrigger: MathJsonSymbol;
};
```

A trigger is the set of tokens that will make an entry in the
LaTeX dictionary eligible to parse the stream and generate an expression.
If the trigger matches, the `parse` handler is called, if available.

The trigger can be specified either as a LaTeX string (`latexTrigger`) or
as an symbol (`symbolTrigger`). A symbol match several
LaTeX expressions that are equivalent, for example `\operatorname{gcd}` or
 `\mathbin{gcd}`, match the `"gcd"` symbol

`matchfix` operators use `openTrigger` and `closeTrigger` instead.

</MemberCard>

<MemberCard>

### BaseEntry {#baseentry}

```ts
type BaseEntry = {
  name: MathJsonSymbol;
  serialize: LatexString | SerializeHandler;
  standaloneSymbol: boolean;
};
```

Maps a string of LaTeX tokens to a function or symbol and vice-versa.

</MemberCard>

<MemberCard>

### DefaultEntry {#defaultentry}

```ts
type DefaultEntry = BaseEntry & Trigger & {
  parse:   | MathJsonExpression
     | ExpressionParseHandler;
};
```

</MemberCard>

<MemberCard>

### ExpressionEntry {#expressionentry}

```ts
type ExpressionEntry = BaseEntry & Trigger & {
  kind: "expression";
  parse:   | MathJsonExpression
     | ExpressionParseHandler;
  precedence: Precedence;
};
```

</MemberCard>

<MemberCard>

### MatchfixEntry {#matchfixentry}

```ts
type MatchfixEntry = BaseEntry & {
  kind: "matchfix";
  openTrigger: Delimiter | LatexToken[];
  closeTrigger: Delimiter | LatexToken[];
  parse: MatchfixParseHandler;
};
```

#### MatchfixEntry.openTrigger

```ts
openTrigger: Delimiter | LatexToken[];
```

If `kind` is `'matchfix'`: the `openTrigger` and `closeTrigger`
properties are required.

#### MatchfixEntry.parse?

```ts
parse?: MatchfixParseHandler;
```

When invoked, the parser is pointing after the close delimiter.
The argument of the handler is the body, i.e. the content between
the open delimiter and the close delimiter.

</MemberCard>

<MemberCard>

### InfixEntry {#infixentry}

```ts
type InfixEntry = BaseEntry & Trigger & {
  kind: "infix";
  associativity: "right" | "left" | "none" | "any";
  precedence: Precedence;
  parse: string | InfixParseHandler;
};
```

#### InfixEntry.kind

```ts
kind: "infix";
```

Infix position, with an operand before and an operand after: `a ⊛ b`.

Example: `+`, `\times`.

#### InfixEntry.associativity?

```ts
associativity?: "right" | "left" | "none" | "any";
```

- **`none`**: a ? b ? c -> syntax error
- **`any`**: a + b + c -> +(a, b, c)
- **`left`**: a / b / c -> /(/(a, b), c)
- **`right`**: a = b = c -> =(a, =(b, c))

- `any`-associative operators have an unlimited number of arguments
- `left`, `right` or `none` associative operators have two arguments

</MemberCard>

<MemberCard>

### PostfixEntry {#postfixentry}

```ts
type PostfixEntry = BaseEntry & Trigger & {
  kind: "postfix";
  precedence: Precedence;
  parse: string | PostfixParseHandler;
};
```

#### PostfixEntry.kind

```ts
kind: "postfix";
```

Postfix position, with an operand before: `a ⊛`

Example: `!`.

</MemberCard>

<MemberCard>

### PrefixEntry {#prefixentry}

```ts
type PrefixEntry = BaseEntry & Trigger & {
  kind: "prefix";
  precedence: Precedence;
  parse: string | PrefixParseHandler;
};
```

#### PrefixEntry.kind

```ts
kind: "prefix";
```

Prefix position, with an operand after: `⊛ a`

Example: `-`, `\not`.

</MemberCard>

<MemberCard>

### EnvironmentEntry {#environmententry}

```ts
type EnvironmentEntry = BaseEntry & {
  kind: "environment";
  parse: EnvironmentParseHandler;
  symbolTrigger: MathJsonSymbol;
};
```

A LaTeX dictionary entry for an environment, that is a LaTeX
construct using `\begin{...}...\end{...}`.

</MemberCard>

<MemberCard>

### SymbolEntry {#symbolentry}

```ts
type SymbolEntry = BaseEntry & Trigger & {
  kind: "symbol";
  precedence: Precedence;
  parse:   | MathJsonExpression
     | SymbolParseHandler;
};
```

#### SymbolEntry.precedence?

```ts
precedence?: Precedence;
```

Used for appropriate wrapping (i.e. when to surround it with parens)

</MemberCard>

<MemberCard>

### FunctionEntry {#functionentry}

```ts
type FunctionEntry = BaseEntry & Trigger & {
  kind: "function";
  parse:   | MathJsonExpression
     | FunctionParseHandler;
  arguments: "enclosure" | "implicit";
};
```

A function is a symbol followed by:
- some postfix operators such as `\prime`
- an optional list of arguments in an enclosure (parentheses)

For more complex situations, for example implicit arguments or
inverse functions postfix (i.e. ^{-1}), use a custom parse handler with a
entry of kind `expression`.

#### FunctionEntry.arguments?

```ts
arguments?: "enclosure" | "implicit";
```

How arguments are parsed:
- `'enclosure'` (default): arguments must be enclosed in parentheses,
  e.g. `\max(a, b)`.
- `'implicit'`: arguments can be provided with or without parentheses,
  e.g. `\det A` is parsed as `\det(A)`.
  Bare arguments are parsed at multiplication precedence, so
  `\det 2A + 1` is parsed as `\det(2A) + 1`.

</MemberCard>

<MemberCard>

### LatexDictionaryEntry {#latexdictionaryentry}

```ts
type LatexDictionaryEntry = OneOf<[
  | ExpressionEntry
  | MatchfixEntry
  | InfixEntry
  | PostfixEntry
  | PrefixEntry
  | SymbolEntry
  | FunctionEntry
  | EnvironmentEntry
| DefaultEntry]>;
```

A dictionary entry is a record that maps a LaTeX token or string of tokens
( a trigger) to a MathJSON expression or to a parsing handler.

To define custom LaTeX parsing and serialization, pass a `LatexSyntax`
instance to the `ComputeEngine` constructor via the `latexSyntax` option.
The `LatexSyntax` `dictionary` option **replaces** the default dictionary, so
start from `LATEX_DICTIONARY` and append your entries:

```ts
import { ComputeEngine, LatexSyntax, LATEX_DICTIONARY } from '@cortex-js/compute-engine';

const ce = new ComputeEngine({
  latexSyntax: new LatexSyntax({ dictionary: [...LATEX_DICTIONARY, myEntry] }),
});
```

</MemberCard>

<MemberCard>

### SymbolResolution {#symbolresolution}

```ts
type SymbolResolution = {
  type:   | BoxedType
     | TypeString;
  subscriptEvaluate: boolean;
};
```

What the ambient environment knows about a declared symbol, as reported by
the ParseLatexOptions.resolveSymbol handler.

Declaration is signaled by the *presence* of this record (the handler
returns `undefined` for an undeclared symbol), so a declared symbol whose
type is not known is `{ type: 'unknown' }` — there is no way to report a
type for an undeclared symbol.

</MemberCard>

<MemberCard>

### ParseLatexOptions {#parselatexoptions}

```ts
type ParseLatexOptions = NumberFormat & {
  strict: boolean;
  skipSpace: boolean;
  parseNumbers: "auto" | "rational" | "decimal" | "never";
  resolveSymbol: (symbol) => SymbolResolution | undefined;
  resolveApplication: (context) => "apply" | "multiply" | undefined;
  parseUnexpectedToken: (lhs, parser) => MathJsonExpression | null;
  preserveLatex: boolean;
  diagnostics: boolean;
  onAmbiguity: "report" | "error";
  quantifierScope: "tight" | "loose";
  timeDerivativeVariable: string;
  tolerance: number;
};
```

The LaTeX parsing options can be used with the `ce.parse()` method.

#### ParseLatexOptions.strict

```ts
strict: boolean;
```

Controls the strictness of LaTeX parsing:

- `true`: Strict LaTeX syntax required (e.g., `\sin{x}`, `x^{n+1}`)
- `false`: Accept relaxed Math-ASCII/Typst-like syntax in addition to
  LaTeX (e.g., `sin(x)`, `x^(n+1)`)

**Default**: `true`

#### ParseLatexOptions.skipSpace

```ts
skipSpace: boolean;
```

If true, ignore space characters in math mode.

**Default**: `true`

#### ParseLatexOptions.parseNumbers

```ts
parseNumbers: "auto" | "rational" | "decimal" | "never";
```

When parsing a decimal number, e.g. `3.1415`:

- `"auto"` or `"decimal"`: if a decimal number, parse it as an approximate
  decimal number with a whole part and a fractional part
- `"rational"`: if a decimal number, parse it as an exact rational number
  with a numerator  and a denominator. If not a decimal number, parse
  it as a regular number.
- `"never"`: do not parse numbers, instead return each token making up
 the number (minus sign, digits, decimal marker, etc...).

Note: if the number includes repeating digits (e.g. `1.33(333)`),
it will be parsed as a decimal number even if this setting is `"rational"`.

**Default**: `"auto"`

#### ParseLatexOptions.resolveSymbol?

```ts
resolveSymbol?: (symbol) => SymbolResolution | undefined;
```

The symbol oracle: invoked when the parser needs to know what the
ambient environment knows about a symbol.

Return `undefined` if the symbol is undeclared, or a [SymbolResolution](#symbolresolution)
record if it is declared. Declaration is the *presence* of the record —
a symbol declared with an `unknown` type is still declared (return
`{ type: 'unknown' }` for it), which is distinct from returning
`undefined`.

Lexical bindings and explicit engine declarations take precedence. This
handler supplies facts for names without an authoritative declaration;
speculative types inferred from earlier uses do not suppress it.
Answers are cached by name for a single parse. Use `resolveApplication`
for notation choices that depend on an occurrence's syntax or position.

Supplied facts belong to the resulting expression: they are retained for
deferred canonicalization, including per-call handlers, without declaring
symbols in the caller's scope. Changing a handler later does not change
the meaning of an already parsed expression.

The `symbol` argument is a [valid symbol](#symbols).

#### ParseLatexOptions.resolveApplication?

```ts
resolveApplication?: (context) => "apply" | "multiply" | undefined;
```

Interpret an unresolved symbol followed by parentheses.

Called after structural parsing for heads without an authoritative type.
Explicit declarations, external symbol facts and lexical parameters take
precedence. Return `undefined` to retain the usual notation heuristics.
Return `apply` or `multiply` to commit an occurrence's reading without
declaring its head. The decision is retained in raw MathJSON and survives
later canonicalization, including when this handler is supplied per-call.

This is a pure syntax policy, not a definition recognizer: a host that uses
`=` for definitions should discover headers and declare them before parsing
bodies. The hook is not called for bare juxtaposition or square brackets.

#### ParseLatexOptions.parseUnexpectedToken

```ts
parseUnexpectedToken: (lhs, parser) => MathJsonExpression | null;
```

This handler is invoked when the parser encounters an unexpected token.

The `lhs` argument is the left-hand side of the token, if any.

The handler can access the unexpected token with `parser.peek`. If
it is a token that should be recognized, the handler can consume it
by calling `parser.nextToken()`.

The handler should return an expression or `null` if the token is not
recognized.

#### ParseLatexOptions.preserveLatex

```ts
preserveLatex: boolean;
```

If true, the expression will be decorated with the LaTeX
fragments corresponding to each elements of the expression.

The top-level expression, that is the one returned by `parse()`, will
include the verbatim LaTeX input that was parsed. The sub-expressions
may contain a slightly different LaTeX, for example with consecutive spaces
replaced by one, with comments removed and with some low-level LaTeX
commands replaced, for example `\egroup` and `\bgroup`.

**Default:** `false`

#### ParseLatexOptions.diagnostics?

```ts
diagnostics?: boolean;
```

If true, collect opt-in parse-time diagnostics (see [ParseDiagnostic](#parsediagnostic))
flagging charitable parse decisions — undeclared symbols, application-like
juxtaposition read as multiply, discarded `%` comments, and trailing noise
dropped by recovery. In non-strict mode, also: letter runs read as a
product (`ambiguous-letter-run`), an implicit product read as the whole
denominator of a `/` (`ambiguous-denominator`), digits
separated by white space read as one number (`ambiguous-digit-groups`), a
symbol directly followed by `.digits` read as a product
(`ambiguous-letter-decimal`), and a prefix `±` or two signs in a row
(`ambiguous-sign`).

This flag only takes effect through
[ComputeEngine.parse](#parse-1), which
wires up the collector and attaches the resulting array to the top-level
parsed expression's `parseDiagnostics` property. On the standalone
`LatexSyntax.parse()` entry point the flag is a silent no-op (that entry
returns plain MathJSON with nowhere to attach diagnostics).

This is purely additive: enabling it never changes the parse output.

**Default:** `false`

#### ParseLatexOptions.onAmbiguity?

```ts
onAmbiguity?: "report" | "error";
```

What the lenient grammar (`strict: false`) does with a reading that has
a second common reading, that is, with each diagnostic whose code starts
with `ambiguous-` (see [ParseDiagnostic](#parsediagnostic)):

- `"report"`: keep the reading. The diagnostic is reported when
  `diagnostics` is `true`.
- `"error"`: put an `Error` node in place of the smallest expression that
  holds the source span of the diagnostic. The error code is the
  diagnostic code, and the error holds the source text of the span:
  `["Error", "'ambiguous-sign'", ["LatexString", "'--'"]]`. This works
  without `diagnostics: true`, and for every code that starts with
  `ambiguous-`.

The parser records the source span of the expressions it builds. When
no recorded expression holds the span of a diagnostic, for example
because a later step rebuilt that part of the result, the `Error` node
replaces the whole result. When two diagnostics select nested
expressions, the `Error` node of the outer expression is kept.

In strict mode (`strict: true`) this option has no effect: the strict
grammar reports no `ambiguous-*` diagnostic.

**Default:** `"report"`

#### ParseLatexOptions.quantifierScope

```ts
quantifierScope: "tight" | "loose";
```

Controls how quantifier scope is determined when parsing expressions
like `\forall x. P(x) \rightarrow Q(x)`.

- `"tight"`: The quantifier binds only to the immediately following
  well-formed formula, stopping at logical connectives (`\rightarrow`,
  `\implies`, `\land`, `\lor`, etc.). This follows standard First-Order
  Logic conventions. Use explicit parentheses for wider scope:
  `\forall x. (P(x) \rightarrow Q(x))`.

- `"loose"`: The quantifier scope extends to the end of the expression
  or until a lower-precedence operator is encountered.

**Default:** `"tight"`

##### Example

```ts
// With "tight" (default):
// \forall x. P(x) \rightarrow Q(x)
// parses as: (∀x. P(x)) → Q(x)

// With "loose":
// \forall x. P(x) \rightarrow Q(x)
// parses as: ∀x. (P(x) → Q(x))
```

#### ParseLatexOptions.timeDerivativeVariable

```ts
timeDerivativeVariable: string;
```

The variable used for time derivatives in Newton notation
(`\dot{x}`, `\ddot{x}`, etc.).

When parsing `\dot{x}`, it will be interpreted as `["D", "x", timeDerivativeVariable]`.

**Default:** `"t"`

#### ParseLatexOptions.tolerance

```ts
tolerance: number;
```

The tolerance used when validating inferred range steps from sampled
elements (e.g. `[0, 0.1, 0.2, \ldots, 1]`). Two consecutive differences
are considered equal when they differ by less than this value.

Populated automatically from `ce.tolerance` by `ce.parse()`.

**Default:** `ce.tolerance` (typically `1e-7`)

</MemberCard>

### Parser {#parser}

An instance of `Parser` is provided to the `parse` handlers of custom
LaTeX dictionary entries.

<MemberCard>

##### Parser.options {#options}

```ts
readonly options: Readonly<ParseLatexOptions>;
```

</MemberCard>

<MemberCard>

##### Parser.inQuantifierScope {#inquantifierscope}

```ts
readonly inQuantifierScope: boolean;
```

True if currently parsing inside a quantifier body (ForAll, Exists, etc.)

</MemberCard>

<MemberCard>

##### Parser.index {#index}

```ts
index: number;
```

The index of the current token

</MemberCard>

<MemberCard>

##### Parser.atEnd {#atend}

```ts
readonly atEnd: boolean;
```

True if the last token has been reached.
Consider also `atTerminator()`.

</MemberCard>

<MemberCard>

##### Parser.peek {#peek}

```ts
readonly peek: string;
```

Return the next token, without advancing the index

</MemberCard>

<MemberCard>

##### Parser.atBoundary {#atboundary}

</MemberCard>

<MemberCard>

##### Parser.environmentName()? {#environmentname}

```ts
environmentName(): string | null
```

The name of the innermost environment (`\begin{name} … \end{name}`)
whose body is being read, or `null` outside an environment. A row of a
`cases` environment records a second reading of an assignment to a
subscripted name (see `parseAssign()` in `definitions-core.ts`).

</MemberCard>

<MemberCard>

##### Parser.\_recordBlockRowAlternative()? {#_recordblockrowalternative}

```ts
_recordBlockRowAlternative(expr, local): void
```

Record `local` as the second reading of the row expression `expr` of a
`cases` environment: the declaration of a block local, which the block
branch of `parseCasesEnvironment()` swaps in when the environment turns
out to be a block.

####### expr

[`MathJsonExpression`](#mathjsonexpression)

####### local

[`MathJsonExpression`](#mathjsonexpression)

</MemberCard>

<MemberCard>

##### Parser.blockRowAlternative()? {#blockrowalternative}

```ts
blockRowAlternative(expr): MathJsonExpression | null
```

The recorded second reading of a row expression, or `null`.

####### expr

[`MathJsonExpression`](#mathjsonexpression)

</MemberCard>

<MemberCard>

##### Parser.binderSymbol() {#bindersymbol}

```ts
binderSymbol(expr): string | null
```

The name that `expr` declares when it is read in a binder position: the
index of a sum or a product, the variable of a comprehension, a function
parameter, a local variable of a `where` clause. A symbol is its own
name. An element access that the symbol parser made from a subscript on
a symbol declared as an indexed collection (`n_{0}` when `n` is a list
is read as `At(n, 0)` everywhere else) is the joined name, `n_0`: a
binder is a new name, whatever its base is declared as. Any other
expression gives `null`.

A custom dictionary entry that binds a name (a `with` clause, a loop
form) reads the binder with this method, not with `parseSymbol()`,
which cannot read `n_{0}` as a new name when `n` is a list. Pass the
expression that `parseExpression()` returned for the binding, or its
left-hand side, and then rewrite the body with
[rebindSubscripts](#rebindsubscripts).

####### expr

  \| [`MathJsonExpression`](#mathjsonexpression)
  \| `null`
  \| `undefined`

</MemberCard>

<MemberCard>

##### Parser.rebindSubscripts() {#rebindsubscripts}

```ts
rebindSubscripts(expr, names): MathJsonExpression
```

Replace, in `expr`, each element access that the symbol parser made from
a subscript on an indexed collection (`At(n, 0)` from `n_{0}`) whose
joined name is one of `names` with that name. A binder calls it on its
body, and on the bindings that follow the declaration, so that the
occurrences of the new name are the name and not an element of the base.
The other parts of `expr` are not changed. The parse of a body that
precedes the clause (`n_{0} + 1 \operatorname{with} n_{0} = 2`, an infix
entry) is rewritten the same way, so a custom clause can bind a name
after its body was read. A `Subscript` that the parser made from a
joined name in the body of an inner sum or product
(`\sum_{m_{n_0}=1}^{3}\sum_{n_0=1}^{2} m_{n_0}`, where the inner sum
reads `m_{n_0}` as `m` indexed by `n_0`) is replaced the same way: here
it is the name `m_n_0`, the index of the outer sum.

####### expr

[`MathJsonExpression`](#mathjsonexpression)

####### names

`ReadonlySet`\<`string`\>

</MemberCard>

<MemberCard>

##### Parser.resolveSymbol() {#resolvesymbol}

```ts
resolveSymbol(id, purpose?): 
  | {
  type: BoxedType;
  subscriptEvaluate: boolean;
  inferred: boolean;
 }
  | undefined
```

The single symbol oracle: everything the parser knows about `id`.

Merges (in priority order) parser-local bindings — sum indices, `Block`/
`Function` parameters, tracked in the parser's symbol table — over the
ParseLatexOptions.resolveSymbol handler (which `ce.parse()` wires
to consult explicit engine declarations before external handlers).

Returns `undefined` if `id` is undeclared. A declared symbol always gets
a record — declaration *presence* is the `!== undefined` check, distinct
from type knowledge: a symbol declared with an `unknown` type still
resolves (with `type.isUnknown` true).

####### id

`string`

####### purpose?

`"indexed-base"`

</MemberCard>

<MemberCard>

##### Parser.isLibraryFunction() {#islibraryfunction}

```ts
isLibraryFunction(id): boolean
```

Whether `id` is a function of a library of the engine, so that a LaTeX
assignment cannot define it. A parameter of a function that the parser is
reading, and the name of that function, are not the library function. A
parser with no engine gives `false`.

####### id

`string`

</MemberCard>

<MemberCard>

##### Parser.isFunctionTriggerName() {#isfunctiontriggername}

```ts
isFunctionTriggerName(name): boolean
```

Whether `name` is claimed by a `kind: 'function'` dictionary entry's
`symbolTrigger` (`log`, `lcm`, `var`, …). Such a name owns its call
syntax — including any subscript, which its parser may bind as an
argument (`\operatorname{log}_2(x)` is `Log(x, 2)`) — so subscript
absorption must not fold `name_sub` into a plain symbol and preempt the
function reading.

####### name

`string`

</MemberCard>

<MemberCard>

##### Parser.pushSymbolTable() {#pushsymboltable}

```ts
pushSymbolTable(): void
```

</MemberCard>

<MemberCard>

##### Parser.popSymbolTable() {#popsymboltable}

```ts
popSymbolTable(): void
```

</MemberCard>

<MemberCard>

##### Parser.addSymbol() {#addsymbol}

```ts
addSymbol(id, type): void
```

####### id

`string`

####### type

`string` \| [`BoxedType`](#boxedtype)

</MemberCard>

<MemberCard>

##### Parser.enterQuantifierScope() {#enterquantifierscope}

```ts
enterQuantifierScope(): void
```

Enter a quantifier scope for parsing the body of ForAll, Exists, etc.

</MemberCard>

<MemberCard>

##### Parser.exitQuantifierScope() {#exitquantifierscope}

```ts
exitQuantifierScope(): void
```

Exit the current quantifier scope

</MemberCard>

<MemberCard>

##### Parser.atTerminator() {#atterminator}

```ts
atTerminator(t): boolean
```

Return true if the terminator condition is met or if the last token
has been reached.

####### t

[`Terminator`](#terminator) \| `undefined`

</MemberCard>

<MemberCard>

##### Parser.nextToken() {#nexttoken}

```ts
nextToken(): string
```

Return the next token and advance the index

</MemberCard>

<MemberCard>

##### Parser.latex() {#latex}

```ts
latex(start, end?): string
```

Return a string representation of the expression
between `start` and `end` (default: the whole expression)

####### start

`number`

####### end?

`number`

</MemberCard>

<MemberCard>

##### Parser.error() {#error}

```ts
error(code, fromToken): MathJsonExpression
```

Return an error expression with the specified code and arguments.

The returned `Error` expression includes `sourceOffsets` metadata with
zero-based, end-exclusive offsets into the serialized LaTeX. Missing-operand
errors use a collapsed (zero-width) range at the position where the operand
was expected.

####### code

`string` \| \[`string`, `...MathJsonExpression[]`\]

####### fromToken

`number`

</MemberCard>

<MemberCard>

##### Parser.sourceOffsets() {#sourceoffsets-1}

```ts
sourceOffsets(startToken, endToken?): [start: number, end: number]
```

Return source offsets for a token range, as zero-based, end-exclusive
character offsets into the serialized LaTeX (`tokensToString`). For input
that round-trips unchanged (e.g. editor-generated LaTeX), these match the
original input string.

####### startToken

`number`

####### endToken?

`number`

</MemberCard>

<MemberCard>

##### Parser.skipSpace() {#skipspace}

```ts
skipSpace(): boolean
```

If there are any space, advance the index until a non-space is encountered

</MemberCard>

<MemberCard>

##### Parser.skipVisualSpace() {#skipvisualspace}

```ts
skipVisualSpace(): void
```

Skip over "visual space" which
includes space tokens, empty groups `{}`, and commands such as `\,` and `\!`

</MemberCard>

<MemberCard>

##### Parser.match() {#match}

```ts
match(token): boolean
```

If the next token matches the target advance and return true. Otherwise
return false

####### token

`string`

</MemberCard>

<MemberCard>

##### Parser.matchAll() {#matchall}

```ts
matchAll(tokens): boolean
```

Return true if the next tokens match the argument, an array of tokens, or null otherwise

####### tokens

`string`[]

</MemberCard>

<MemberCard>

##### Parser.matchAny() {#matchany}

```ts
matchAny(tokens): string
```

Return the next token if it matches any of the token in the argument or null otherwise

####### tokens

`string`[]

</MemberCard>

<MemberCard>

##### Parser.parseChar() {#parsechar}

```ts
parseChar(): string | null
```

If the next token is a character, return it and advance the index
This includes plain characters (e.g. 'a', '+'...), characters
defined in hex (^^ and ^^^^), the `\char` and `\unicode` command.

</MemberCard>

<MemberCard>

##### Parser.parseGroup() {#parsegroup}

```ts
parseGroup(): MathJsonExpression | null
```

Parse an expression in a LaTeX group enclosed in curly brackets `{}`.
These are often used as arguments to LaTeX commands, for example
`\frac{1}{2}`.

Return `null` if none was found
Return `Nothing` if an empty group `{}` was found

</MemberCard>

<MemberCard>

##### Parser.parseToken() {#parsetoken}

```ts
parseToken(): MathJsonExpression | null
```

Some LaTeX commands (but not all) can accept arguments as single
tokens (i.e. without braces), for example `^2`, `\sqrt3` or `\frac12`

This argument will usually be a single token, but can be a sequence of
tokens (e.g. `\sqrt\frac12` or `\sqrt\operatorname{speed}`).

The following tokens are excluded from consideration in order to fail
early when encountering a likely syntax error, for example `x^(2)`
instead of `x^{2}`. With `(` in the list of excluded tokens, the
match will fail and the error can be recovered.

The excluded tokens include `!"#$%&(),/;:?@[]`|~", `\left`, `\bigl`, etc...

</MemberCard>

<MemberCard>

##### Parser.parseOptionalGroup() {#parseoptionalgroup}

```ts
parseOptionalGroup(): MathJsonExpression | null
```

Parse an expression enclosed in a LaTeX optional group enclosed in square brackets `[]`.

Return `null` if none was found.

</MemberCard>

<MemberCard>

##### Parser.parseEnclosure() {#parseenclosure}

```ts
parseEnclosure(): MathJsonExpression | null
```

Parse an enclosure (open paren/close paren, etc..) and return the expression inside the enclosure

</MemberCard>

<MemberCard>

##### Parser.parseStringGroup() {#parsestringgroup}

```ts
parseStringGroup(optional?, rawTokens?): string | null
```

Some LaTeX commands have arguments that are not interpreted as
expressions, but as strings. For example, `\begin{array}{ccc}` (both
`array` and `ccc` are strings), `\color{red}` or `\operatorname{lim sup}`.

If the next token is the start of a group (`{`), return the content
of the group as a string. This may include white space, and it may need
to be trimmed at the start and end of the string.

LaTeX commands are typically not allowed inside a string group (for example,
`\alpha` would result in an error), but we do not enforce this.

If `optional` is true, this should be an optional group in square brackets
otherwise it is a regular group in braces.

If `rawTokens` is provided, the raw (un-normalized) tokens of the group
content are appended to it — useful when the same content must be matched
verbatim later (the returned string normalizes commands such as `\alpha`
to unicode, which is lossy).

####### optional?

`boolean`

####### rawTokens?

`string`[]

</MemberCard>

<MemberCard>

##### Parser.parseSymbol() {#parsesymbol}

```ts
parseSymbol(until?): MathJsonExpression | null
```

A symbol can be:
- a single-letter symbol: `x`
- a single LaTeX command: `\pi`
- a multi-letter symbol: `\operatorname{speed}`

####### until?

`Partial`\<[`Terminator`](#terminator)\>

</MemberCard>

<MemberCard>

##### Parser.parseTabular() {#parsetabular}

```ts
parseTabular(): 
  | MathJsonExpression[][]
  | null
```

Parse an expression in a tabular format, where rows are separated by `\\`
and columns by `&`.

Return rows of sparse columns: empty rows are indicated with `Nothing`,
and empty cells are also indicated with `Nothing`.

</MemberCard>

<MemberCard>

##### Parser.parseArguments() {#parsearguments}

```ts
parseArguments(kind?, until?): 
  | readonly MathJsonExpression[]
  | null
```

Parse an argument list, for example: `(12, x+1)` or `\left(x\right)`

- 'enclosure' : will look for arguments inside an enclosure
   (an open/close fence) (**default**)
- 'implicit': either an expression inside a pair of `()`, or just a primary
   (i.e. we interpret `\cos x + 1` as `\cos(x) + 1`)

Return an array of expressions, one for each argument, or `null` if no
argument was found.

####### kind?

`"enclosure"` \| `"implicit"`

####### until?

[`Terminator`](#terminator)

</MemberCard>

<MemberCard>

##### Parser.parseBraceArguments() {#parsebracearguments}

```ts
parseBraceArguments(): 
  | readonly MathJsonExpression[]
  | null
```

Parse one or more `{...}` groups as an argument list, exactly as if
they were a parenthesized argument list: `\gcd{a,b}` ≡ `\gcd(a,b)`,
and consecutive groups are successive arguments (`\mod{x}{2}` ≡
`\mod(x,2)`, the TeX multi-argument-macro habit). A group whose
content is a comma sequence contributes each element as an argument.

An empty group is not an argument (`{}` is spacing/grouping
decoration), and no group at all returns `null`.

Used as a fallback after `parseArguments('enclosure')` for
dictionary-registered function heads, where the writer's intent is
unambiguous even though the braces render invisibly.

</MemberCard>

<MemberCard>

##### Parser.parsePostfixOperator() {#parsepostfixoperator}

```ts
parsePostfixOperator(lhs, until?): MathJsonExpression | null
```

Parse a postfix operator, such as `'` or `!`.

Prefix, infix and matchfix operators are handled by `parseExpression()`

####### lhs

[`MathJsonExpression`](#mathjsonexpression) \| `null`

####### until?

`Partial`\<[`Terminator`](#terminator)\>

</MemberCard>

<MemberCard>

##### Parser.parseExpression() {#parseexpression}

```ts
parseExpression(until?): MathJsonExpression | null
```

Parse an expression:

```
<expression> ::=
 | <primary> ( <infix-op> <expression> )?
 | <prefix-op> <expression>

<primary> :=
  (<number> | <symbol> | <function-call> | <matchfix-expr>)
  (<subsup> | <postfix-operator>)*

<matchfix-expr> :=
  <matchfix-op-open> <expression> <matchfix-op-close>

<function-call> ::=
  | <function><matchfix-op-group-open><expression>[',' <expression>]<matchfix-op-group-close>
```

This is the top-level parsing entry point.

Stop when an operator of precedence less than `until.minPrec`
or the sequence of tokens `until.tokens` is encountered

`until` is `{ minPrec:0 }` by default.

####### until?

`Partial`\<[`Terminator`](#terminator)\>

</MemberCard>

<MemberCard>

##### Parser.parseNumber() {#parsenumber}

```ts
parseNumber(): MathJsonExpression | null
```

Parse a number.

</MemberCard>

<MemberCard>

##### Parser.addBoundary() {#addboundary}

```ts
addBoundary(boundary): void
```

Boundaries are used to detect the end of an expression.

They are used for unusual syntactic constructs, for example
`\int \sin x dx` where the `dx` is not an argument to the `\sin`
function, but a boundary of the integral.

They are also useful when handling syntax errors and recovery.

For example, `\begin{bmatrix} 1 & 2 { \end{bmatrix}` has an
extraneous `{`, but the parser will attempt to recover and continue
parsing when it encounters the `\end{bmatrix}` boundary.

####### boundary

`string`[]

</MemberCard>

<MemberCard>

##### Parser.removeBoundary() {#removeboundary}

```ts
removeBoundary(): void
```

</MemberCard>

<MemberCard>

##### Parser.matchBoundary() {#matchboundary}

```ts
matchBoundary(): boolean
```

</MemberCard>

<MemberCard>

##### Parser.boundaryError() {#boundaryerror}

```ts
boundaryError(msg): MathJsonExpression
```

####### msg

`string` \| \[`string`, `...MathJsonExpression[]`\]

</MemberCard>

<MemberCard>

### RootStyle {#rootstyle}

```ts
type RootStyle = "radical" | "quotient" | "solidus";
```

How to serialize a root, i.e. `\sqrt{x}`, `x^{1/2}` or `x^\frac12`.

</MemberCard>

<MemberCard>

### FractionStyle {#fractionstyle}

```ts
type FractionStyle = 
  | "quotient"
  | "block-quotient"
  | "inline-quotient"
  | "inline-solidus"
  | "nice-solidus"
  | "reciprocal"
  | "factor";
```

How to serialize a fraction.

</MemberCard>

<MemberCard>

### LogicStyle {#logicstyle}

```ts
type LogicStyle = "word" | "boolean" | "uppercase-word" | "punctuation";
```

How to serialize the logic operators.

</MemberCard>

<MemberCard>

### PowerStyle {#powerstyle}

```ts
type PowerStyle = "root" | "solidus" | "quotient";
```

How to serialize a fractional power.

</MemberCard>

<MemberCard>

### NumericSetStyle {#numericsetstyle}

```ts
type NumericSetStyle = "compact" | "regular" | "interval" | "set-builder";
```

How to serialize a numeric set, i.e. `\R^*`, `\R \setminus \lbrace 0\rbrace`.

</MemberCard>

<MemberCard>

### IndexStyle {#indexstyle}

```ts
type IndexStyle = "subscript" | "bracket";
```

How to serialize collection indexing (the `At` operator).

</MemberCard>

<MemberCard>

### StyleOption {#styleoption}

```ts
type StyleOption<T> = T | ((expr, level) => T);
```

A serialization style option: either a constant, or a function of the
expression and of its nesting level.

#### Type Parameters

• T extends `string`

</MemberCard>

<MemberCard>

### SerializeLatexOptions {#serializelatexoptions}

```ts
type SerializeLatexOptions = NumberSerializationFormat & {
  prettify: boolean;
  materialization: boolean | number | [number, number];
  exponentialE: LatexString;
  invisibleMultiply: LatexString;
  invisiblePlus: LatexString;
  multiply: LatexString;
  missingSymbol: LatexString;
  keywordStyle: "text" | "keyword" | "operatorname";
  applyFunctionStyle: StyleOption<DelimiterScale>;
  groupStyle: StyleOption<DelimiterScale>;
  rootStyle: StyleOption<RootStyle>;
  fractionStyle: StyleOption<FractionStyle>;
  logicStyle: StyleOption<LogicStyle>;
  powerStyle: StyleOption<PowerStyle>;
  numericSetStyle: StyleOption<NumericSetStyle>;
  indexStyle: StyleOption<IndexStyle>;
  dotNotation: boolean;
  dmsFormat: boolean;
  angleNormalization: "none" | "0...360" | "-180...180";
};
```

The LaTeX serialization options can used with the `expr.toLatex()` method.

#### SerializeLatexOptions.prettify

```ts
prettify: boolean;
```

If true, prettify the LaTeX output.

For example, render `x\cdot y^{-1}` as `\frac{x}{y}`, and
`\frac{1}{a}\cdot\frac{1}{b}` as `\frac{1}{ab}`. A product whose only
denominators are those of quotients with a numerator other than 1 keeps
its factors, so that it reads back as the same expression:
`90\frac{x}{y}` stays `90\times\frac{x}{y}`.

#### SerializeLatexOptions.materialization

```ts
materialization: boolean | number | [number, number];
```

Controls the materialization of the lazy collections.

- If `true`, lazy collections are materialized, i.e. it is rendered as a
  LaTeX expression with all its elements.
- If `false`, the expression is not materialized, i.e. it is
  rendered as a LaTeX command with its arguments.
- If a number is provided, it is the maximum number of elements
  that will be materialized.
- If a pair of numbers is provided, it is the number of elements
  of the head and the tail that will be materialized, respectively.

#### SerializeLatexOptions.exponentialE?

```ts
exponentialE?: LatexString;
```

LaTeX used to render the constant `ExponentialE`, the counterpart of
`imaginaryUnit`. Use `e` or `\mathrm{e}` to match the glyph used for
the imaginary unit.

Serialization only: `\exponentialE`, `\mathrm{e}` and `\operatorname{e}`
are always read as the constant.

##### Default

`\exponentialE`

#### SerializeLatexOptions.invisibleMultiply

```ts
invisibleMultiply: LatexString;
```

LaTeX string used to render an invisible multiply, e.g. in '2x'.

If empty, both operands are concatenated, i.e. `2x`.

Use `\cdot` to insert a `\cdot` operator between them, i.e. `2 \cdot x`.

Empty by default.

#### SerializeLatexOptions.invisiblePlus

```ts
invisiblePlus: LatexString;
```

LaTeX string used to render [mixed numbers](https://en.wikipedia.org/wiki/Fraction#Mixed_numbers) e.g. '1 3/4'.

Leave it empty to join the main number and the fraction, i.e. render it
as `1\frac{3}{4}`.

Use `+` to insert an explicit `+` operator between them,
 i.e. `1+\frac{3}{4}`

Empty by default.

#### SerializeLatexOptions.multiply

```ts
multiply: LatexString;
```

LaTeX string used to render an explicit multiply operator.

For example, `\times`, `\cdot`, etc...

Default: `\times`

#### SerializeLatexOptions.missingSymbol

```ts
missingSymbol: LatexString;
```

Serialize the expression `["Error", "'missing'"]`,  with this LaTeX string

#### SerializeLatexOptions.keywordStyle

```ts
keywordStyle: "text" | "keyword" | "operatorname";
```

How to serialize keyword constructs (`if`/`then`/`else`, `for`, `where`,
`and`, `or`, the quantifiers, …).

- `'text'` (default): `\text{if }`, `\text{ then }`, … — the conventional
  spelling. Spacing is encoded manually inside the braces.
- `'keyword'`: `\keyword{if}`, `\keyword{then}`, … — a math-mode command
  whose renderer applies symmetric keyword spacing. Requires the rendering
  environment to define `\keyword`.
- `'operatorname'`: `\operatorname{if}`, … — operator-name spacing.

All three spellings parse back to the same expression.

##### Default

```ts
'text'
```

#### SerializeLatexOptions.indexStyle

```ts
indexStyle: StyleOption<IndexStyle>;
```

Notation used to serialize collection indexing (the `At` operator), e.g.
`["At", v, 1]`.

- `'bracket'` (default): `v[1]`, `M[i,j]` — programming-style indexing,
  which always round-trips back to `At` even when the collection symbol
  is not declared.
- `'subscript'`: `v_1`, `M_{i,j}` — conventional mathematical notation,
  symmetric with how subscript indexing of an `indexed_collection`
  parses; only round-trips when the base is declared as a collection.

#### SerializeLatexOptions.dotNotation

```ts
dotNotation: boolean;
```

When `true`, member-access heads serialize to dot notation:
- `PointX(p)` → `p.x`
- `PointY(p)` → `p.y`
- `PointZ(p)` → `p.z`
- `Real(z)` → `z.\operatorname{real}`
- `Imaginary(z)` → `z.\operatorname{imag}`
- `Length(L)` → `L.\operatorname{count}`
- `Sum(L)` → `L.\operatorname{total}`
- `Max(L)` → `L.\max`
- `Min(L)` → `L.\min`
- `Mean(L)` → `L.\operatorname{mean}`
- `Median(L)` → `L.\operatorname{median}`
- `StandardDeviation(L)` → `L.\operatorname{stdev}`
- `Sort(L)` → `L.\operatorname{sort}`
- `Unique(L)` → `L.\operatorname{unique}`

When `false` (default), the standard function-call form is used.

Only applies to arity-1 forms. Multi-operand forms (e.g. `Sum` with
an index tuple) keep their standard serialization even when this is `true`.

**Serializer-only.** This flag has no effect on parsing. All input
forms continue to parse as before regardless of the flag (e.g. `|L|`,
`\operatorname{count}(L)`, and `L.\operatorname{count}` all parse to
`["Length", L]` whether `dotNotation` is on or off). The flag only
decides which form the serializer emits.

Set engine-wide via `ce.latexOptions.dotNotation = true`, or per-call
via `expr.toLatex({ dotNotation: true })`.

**Default**: `false`

#### SerializeLatexOptions.dmsFormat?

```ts
dmsFormat?: boolean;
```

When true, serialize angle quantities in degrees-minutes-seconds format.
When false (default), use decimal degrees.

##### Default

```ts
false
```

##### Example

```typescript
const ce = new ComputeEngine();
const angle = ce.expr(['Quantity', 9.5, 'deg']);

// DMS format
angle.latex({ dmsFormat: true });  // "9°30'"

// Decimal format (default)
angle.latex({ dmsFormat: false }); // "9.5°"

// Full DMS notation
ce.expr(['Quantity', 9.504166, 'deg'])
  .latex({ dmsFormat: true });     // "9°30'15\""
```

#### SerializeLatexOptions.angleNormalization?

```ts
angleNormalization?: "none" | "0...360" | "-180...180";
```

Normalize angles to a specific range during serialization.
Useful for geographic coordinates and rotations.

##### Default

```ts
'none'
```

##### Example

```typescript
const ce = new ComputeEngine();

// No normalization (show exact value)
ce.expr(['Degrees', 370])
  .latex({ angleNormalization: 'none' });  // "370°"

// Normalize to [0, 360) - useful for bearings
ce.expr(['Degrees', 370])
  .latex({ angleNormalization: '0...360' }); // "10°"

ce.expr(['Degrees', -45])
  .latex({ angleNormalization: '0...360' }); // "315°"

// Normalize to [-180, 180] - useful for longitude
ce.expr(['Degrees', 190])
  .latex({ angleNormalization: '-180...180' }); // "-170°"

// Combine with DMS format
ce.expr(['Degrees', 370])
  .latex({
    dmsFormat: true,
    angleNormalization: '0...360'
  }); // "10°0'0\""
```

</MemberCard>

<MemberCard>

### ResolvedSerializeLatexOptions {#resolvedserializelatexoptions}

```ts
type ResolvedSerializeLatexOptions = Omit<SerializeLatexOptions, 
  | "applyFunctionStyle"
  | "groupStyle"
  | "rootStyle"
  | "fractionStyle"
  | "logicStyle"
  | "powerStyle"
  | "numericSetStyle"
  | "indexStyle"
  | "readsAsPointList"
  | "readsAsCardinality"
  | "readsAsMatrixPowerBase"
  | "readsAsFunctionSymbol"> & {
  readsAsPointList: ((operands) => boolean | undefined) | undefined;
  readsAsCardinality: ((operand) => boolean | undefined) | undefined;
  readsAsMatrixPowerBase: ((base) => boolean | undefined) | undefined;
  readsAsFunctionSymbol: ((name) => boolean | undefined) | undefined;
  applyFunctionStyle: (expr, level) => DelimiterScale;
  groupStyle: (expr, level) => DelimiterScale;
  rootStyle: (expr, level) => RootStyle;
  fractionStyle: (expr, level) => FractionStyle;
  logicStyle: (expr, level) => LogicStyle;
  powerStyle: (expr, level) => PowerStyle;
  numericSetStyle: (expr, level) => NumericSetStyle;
  indexStyle: (expr, level) => IndexStyle;
};
```

The serialization options as seen by the serializer: the style options
have been normalized from their constant form (e.g. `rootStyle: 'solidus'`)
to their function form.

</MemberCard>

### Serializer {#serializer}

An instance of `Serializer` is provided to the `serialize` handlers of custom
LaTeX dictionary entries.

<MemberCard>

##### Serializer.options {#options-1}

```ts
readonly options: Required<ResolvedSerializeLatexOptions>;
```

</MemberCard>

<MemberCard>

##### Serializer.dictionary {#dictionary-1}

```ts
readonly dictionary: SerializerDictionary;
```

</MemberCard>

<MemberCard>

##### Serializer.level {#level}

```ts
level: number;
```

"depth" of the expression:
- 0 for the root
- 1 for a subexpression of the root
- 2 for subexpressions of the subexpressions of the root
- etc...

This allows the serialized LaTeX to vary depending on the depth of the
expression.

For example use `\Bigl(` for the top level, and `\bigl(` or `(` for others.

</MemberCard>

<MemberCard>

##### Serializer.depth {#depth}

```ts
readonly depth: number;
```

How deeply the expression being written is nested: 0 for the expression
`serialize()` was called on, 1 for one of its operands, and so on. Unlike
`level`, no serializer adjusts it, so it tells whether the expression is
an operand of another one.

</MemberCard>

<MemberCard>

##### Serializer.serialize {#serialize-1}

```ts
serialize: (expr) => string;
```

Output a LaTeX string representing the expression

</MemberCard>

<MemberCard>

##### Serializer.wrap {#wrap}

```ts
wrap: (expr, prec?) => string;
```

Add a group fence around the expression if it is
an operator of precedence less than or equal to `prec`.

</MemberCard>

<MemberCard>

##### Serializer.applyFunctionStyle {#applyfunctionstyle}

```ts
applyFunctionStyle: (expr, level) => DelimiterScale;
```

Styles

</MemberCard>

<MemberCard>

##### Serializer.groupStyle {#groupstyle}

```ts
groupStyle: (expr, level) => DelimiterScale;
```

</MemberCard>

<MemberCard>

##### Serializer.rootStyle {#rootstyle-1}

```ts
rootStyle: (expr, level) => "radical" | "quotient" | "solidus";
```

</MemberCard>

<MemberCard>

##### Serializer.fractionStyle {#fractionstyle-1}

```ts
fractionStyle: (expr, level) => 
  | "quotient"
  | "block-quotient"
  | "inline-quotient"
  | "inline-solidus"
  | "nice-solidus"
  | "reciprocal"
  | "factor";
```

</MemberCard>

<MemberCard>

##### Serializer.logicStyle {#logicstyle-1}

```ts
logicStyle: (expr, level) => "boolean" | "word" | "uppercase-word" | "punctuation";
```

</MemberCard>

<MemberCard>

##### Serializer.powerStyle {#powerstyle-1}

```ts
powerStyle: (expr, level) => "quotient" | "solidus" | "root";
```

</MemberCard>

<MemberCard>

##### Serializer.numericSetStyle {#numericsetstyle-1}

```ts
numericSetStyle: (expr, level) => "compact" | "regular" | "interval" | "set-builder";
```

</MemberCard>

<MemberCard>

##### Serializer.indexStyle {#indexstyle-1}

```ts
indexStyle: (expr, level) => "subscript" | "bracket";
```

</MemberCard>

<MemberCard>

##### Serializer.serializeAtDepth() {#serializeatdepth}

```ts
serializeAtDepth(expr, depth): string
```

Serialize `expr` as if it stood at nesting `depth` (0 for the root), for
a serializer that writes the same expression again in another form, or
for an operand whose parent already writes the parentheses it would add.

####### expr

  \| [`MathJsonExpression`](#mathjsonexpression)
  \| `null`
  \| `undefined`

####### depth

`number`

</MemberCard>

<MemberCard>

##### Serializer.serializeFunction() {#serializefunction}

```ts
serializeFunction(expr, def?): string
```

####### expr

[`MathJsonExpression`](#mathjsonexpression)

####### def?

`SerializerDictionaryEntry`

</MemberCard>

<MemberCard>

##### Serializer.serializeSymbol() {#serializesymbol}

```ts
serializeSymbol(expr): string
```

####### expr

[`MathJsonExpression`](#mathjsonexpression)

</MemberCard>

<MemberCard>

##### Serializer.wrapString() {#wrapstring}

```ts
wrapString(s, style, delimiters?): string
```

Output `s` surrounded by delimiters.

If `delimiters` is not specified, use `()`

####### s

`string`

####### style

[`DelimiterScale`](#delimiterscale)

####### delimiters?

`string`

</MemberCard>

<MemberCard>

##### Serializer.wrapArguments() {#wraparguments}

```ts
wrapArguments(expr): string
```

A string with the arguments of expr fenced appropriately and separated by
commas.

####### expr

[`MathJsonExpression`](#mathjsonexpression)

</MemberCard>

<MemberCard>

##### Serializer.wrapShort() {#wrapshort}

```ts
wrapShort(expr): string
```

Add a group fence around the expression if it is
short (not a function)

####### expr

  \| [`MathJsonExpression`](#mathjsonexpression)
  \| `null`
  \| `undefined`

</MemberCard>

<MemberCard>

##### Serializer.wrapPowerBase() {#wrappowerbase}

```ts
wrapPowerBase(expr): string
```

Like `wrapShort`, but for a base directly under a `^` (the base of a
`Power`/`Square`, or of a `Root` written in exponent form: the solidus
or quotient root style), where a nested power or a
postfix `Factorial` also needs a fence.

####### expr

  \| [`MathJsonExpression`](#mathjsonexpression)
  \| `null`
  \| `undefined`

</MemberCard>

<MemberCard>

### SerializeHandler {#serializehandler}

```ts
type SerializeHandler = (serializer, expr) => string;
```

The `serialize` handler of a custom LaTeX dictionary entry can be
a function of this type.

</MemberCard>

<MemberCard>

### ParseDiagnostic {#parsediagnostic}

```ts
type ParseDiagnostic = {
  code: string;
  start: number;
  end: number;
  detail: Record<string, unknown>;
};
```

An opt-in parse-time diagnostic, collected when a LaTeX string is parsed
with `ce.parse(latex, { diagnostics: true })` and exposed on the top-level
result via `Expression.parseDiagnostics`.

Diagnostics flag *charitable* parse decisions that are usually errors in
machine-generated LaTeX (LLM output, OCR): a name read as multiplication
where the source looked like a function application, a reference to an
undeclared symbol, an unescaped `%` that discarded input, or trailing noise
silently dropped by error recovery. They are additive metadata — enabling
them never changes the parse output.

### Codes (`code`, an open enum)

- `"undeclared-symbol"` — a parsed symbol reference resolves to no
  declaration (neither a parser-local binding such as a sum index, nor a
  definition in the engine scope). `detail: { name, type }` where `type` is
  the string form of the resolved type (`"unknown"`). Fires at every
  reference site, including plain variables like `x`.
- `"juxtaposition-as-multiply"` — a symbol immediately followed by a
  delimited group `(…)` or a matrix environment was read as multiplication
  rather than function application. `detail: { name, declaredAs }` with
  `declaredAs` one of `"unknown" | "value" | "function"`. `name` is the
  source symbol even when it was lexed as a unit (`\mathrm{N}(2)`) or
  segmented into a letter run (`divisors(60)` → `"divisors"`). When the
  symbol was read as a unit, `detail` additionally carries
  `lexedAs: "unit"`.
- `"ambiguous-letter-run"` — non-strict mode only: a run of two or more
  letters that is not a known word was read as a product of its parts
  (`eps` → `e·p·s`, `sinx` → `s·i·n·x`, `xpi` → `x·π`). `detail: { run,
  parts }` with `run` the letters as written and `parts` the MathJSON
  symbols it was read as. The diagnostic span is the run. Not emitted for
  explicit products such as `a*b*c`, nor for a run read as one name (a
  bare function name, a spelled-out Greek letter, a letter run before a
  parenthesis), nor for a differential `d` and one letter that is the
  numerator or denominator of a differential quotient (`dy/dx`,
  `\frac{dy}{dx}`). Also emitted when an unbraced superscript or
  subscript takes only the first letter of a run (`e^xy` → `e^x·y`,
  `x^ab` → `x^a·b`): the span is then the whole run, and `parts` is the
  script and the rest of the run as written.
- `"comment-discarded"` — an unescaped `%` discarded the rest of a line.
  `detail: { discardedLength }`.
- `"recovered"` — trailing tokens skipped/coerced by non-strict error
  recovery that do not otherwise surface as an `Error` node. `detail` may
  include the skipped fragment as `{ skipped }`.
- `"ambiguous-denominator"` — non-strict mode only: the
  denominator of a `/` or `÷` is an implicit product, which binds tighter
  than `/`. `1/2x` is read as `1/(2x)`, not `(1/2)x`. The span covers the
  denominator. A differential denominator (`dy/dx`) is not reported.
- `"ambiguous-digit-groups"` — non-strict mode only: white space between
  digits was read as part of one number (`2 3` → 23, `1 000` → 1000,
  `3 .5` → 3.5). `detail: { digits }`. Visual space commands (`1\,000`) and the `{,}`
  separator are not reported.
- `"ambiguous-letter-decimal"` — non-strict mode only: a symbol is directly
  followed by `.digits` (`x.5`), read as the product `x \cdot 0.5`.
  `detail: { name }`. The span starts at the `.`.
- `"ambiguous-sign"` — non-strict mode only: a prefix `±` (also spelled
  `\pm`, `\plusmn` or `+-`) with no left operand, read as a measurement
  with a nominal value of 0 where a person often means two values
  (`x = ±1` is read as `Measurement(0, 1)`, and `y = +-\sqrt{x}` as
  `Measurement(0, √x)`), a prefix `∓` (also spelled `\mp` or `-+`) with
  no left operand, read as `MinusPlus(0, …)` (`x = ∓1` and `-+x` are
  read as `MinusPlus(0, 1)` and `MinusPlus(0, x)`), or two signs in a row
  (`--x`, `x - -y`, `a + -b`, and `a -+ b`, which is read as
  `MinusPlus(a, b)`).
  `detail: { signs }`, the signs as written with no white space. The span
  covers the signs. `a +- b` with no white space is read as
  `Measurement(a, b)` and is not reported.
- Non-strict mode only, codes for a reading that has a second common
  reading (the reading does not change):
  - `"ambiguous-exponent-end"` — where an unbraced exponent ends:
    `e^2pi` (`e^2·π`), `e^i pi`, `e^x/2`, `x^1/2`. `detail: { exponent }`.
    The span is from the base to the end of the operand after the
    exponent: `e^2pi`.
  - `"ambiguous-implicit-subscript"` — a letter followed by digits is a
    subscript (`x2` → `x_2`), and a digit subscript ends before a letter
    (`x_1y` → `x_1·y`). `detail: { base?, subscript }`.
  - `"ambiguous-name-digits"` — letters and digits that are not a library
    function, before a parenthesis: `atan3(y)` → `arctan(3y)`.
    `detail: { name }`.
  - `"ambiguous-function-argument"` — a bare function name with an
    argument of more than one factor and no parentheses (`sin x y` →
    `sin(xy)`), or `log` and a number after white space (`log 2 x` →
    `log_2(x)`), or an argument with no parentheses that starts with `+`
    (`ln+1` → `ln(1)`). `detail: { function }`.
  - `"ambiguous-function-subscript"` — a bare function name other than
    `log` with a subscript, read as the strict grammar reads it:
    `ln_3(x)` → `Log(x, 3)`, `tan_1x` → `Apply(Subscript(Tan, 1), x)`.
    A person can mean a name such as `tan_1`. `detail: { name, subscript }`.
  - `"ambiguous-function-without-parentheses"` — a symbol declared as a
    function followed by an operand: `f x` → `f·x`. `detail: { name }`.
  - `"ambiguous-name-then-number"` — a name, white space, a number:
    `x 2` → `x·2`. `detail: { name }`.
  - `"ambiguous-delta"` — `Δ` or `Delta` followed by a letter: `Δx` →
    `Δ·x`.
  - `"ambiguous-constant-name"` — a library constant alone on the left of
    `=` (`e = 1.6e-19`, `pi = 3.14`), or followed by a parenthesized group
    on the left of `=` (`pi(x) = x` → `π·x = x`, where a person can mean
    the definition of a function `pi`). `detail: { name }`. Only an `=`
    at the top level of the line is reported: the index of
    `\sum_{i=1}^n` is not.
  - `"ambiguous-log-base"` — `log` with two arguments in parentheses:
    `log(x, 2)` is `Log(x, 2)`, the base second, and other tools put the
    base first. Also the name `lg`, which is the base-10 logarithm and,
    in computer science, the base-2 logarithm. `detail: { name }`.
  - `"ambiguous-engine-operator"` — a one-letter library operator written
    as a plain letter before a parenthesis, read as a call of the
    operator: `N(x)` (numeric evaluation), `D(x)` (derivative). A person
    usually means a function of their own. `\operatorname{N}(x)` is not
    reported. `detail: { name }`.
  - `"ambiguous-lookalike-letter"` — a Greek letter that looks like a
    Latin letter (`Α`, `Ρ`, `ο`). `detail: { letter }`.
  - `"ambiguous-unknown-character"` — a character that is not math, read
    as a string: `y = ж`. `detail: { text }`.
  - `"ambiguous-radical"` — the extent of `√` without braces or
    parentheses: `√2π` → `√2·π`, `√x²` → `(√x)²`, `3√8` → `3·√8`. The
    span ends after the operand that follows the radicand.
  - `"ambiguous-absolute-value"` — bars that pair two ways: `|x|y|z|`.
  - `"ambiguous-equation-number"` — a parenthesized number or letter at
    the end of the line, after white space, read as a factor
    (`y = x^2 (2)`, `x = 4 (m)`). The span is the group.
  - `"ambiguous-group-product"` — a parenthesized name followed by a
    parenthesized group with a comma, read as a product (`(x)(1,2)`).
  - `"ambiguous-factorial"` — `!=` directly after an operand, read as
    `≠` (`5!=120`). The span is the `!=`.
  - `"ambiguous-arrow"` — `<-`, read as `< -` (`x <- 2`).
  - `"ambiguous-equal-chain"` — more than one `=` in a chain
    (`x = x = x`). The span is from the first to the last `=`.
  - `"ambiguous-element"` — `in`, `\in` or `∈` whose left operand is an
    equation (`y = x in [0,1]`). The span is the operator.
  - `"ambiguous-interval"` — after `in`, `\in`, `∈` or `\notin`, a
    bracket pair `[a, b]` or `(a, b)`, or a range `[a..b]`, followed by
    an operator, so the pair is not read as an interval:
    `M in [0,1]^2` → `Element(M, Power(List(0, 1), 2))`. The span is the
    bracket pair and the operator after it, with the operand of a `^` or
    a `/` (`[0,1]^2`). `M in [0,1]` is not reported.
  - `"ambiguous-range"` — a range with two `..` (`1..10..2`), a range
    with one `..` next to an operation (`1..5/2`), or `...` directly
    followed by a digit after a decimal number (`.5...5`, which can be
    `.5..` and `.5`).
  - `"ambiguous-percent"` — a `%` after a number (`y = 50%`), which
    starts a comment. The span is the number and the `%`, in
    original-input coordinates.
  - `"ambiguous-comma"` — a comma outside every bracket (`1,5`).
  - `"ambiguous-list-label"` — a list label read as math: `1. y = x`,
    `x = 1. 5`, `(1) y = x`, `a) y = x`, or a line that is only `1.`,
    `(1)`, `(i)` or `[1]`. A letter label is one of `a` to `h`, and only
    when more follows it: a line that is only `(x)` is not reported.
  - `"ambiguous-number-notation"` — `1_000` or `0x10`.
    `detail: { notation }`, `"digit-grouping"` or `"hexadecimal"`.
  - `"ambiguous-date"` — digit groups joined by `-` or `/` that can be a
    date, a phone number or a range (`2026-10-15`, `9/30/2026`,
    `555-1234`, `7-11`). `3/4`, `2-1` and two groups in parentheses
    (`x = (1-10)`) are not reported.

  Their spans use the normalized-LaTeX convention below, except
  `ambiguous-percent`.

### Span convention (`start`/`end`)

Spans for `undeclared-symbol`, `juxtaposition-as-multiply` and every
`ambiguous-*` code except `ambiguous-percent` are offsets into CE's
**normalized** LaTeX (the
re-serialized token stream), which matches the original input only when
the input round-trips unchanged. A Unicode superscript or subscript is the
exception: it is measured as written, not as its expansion, so `x²! + 1`
reports the span `x²!` (offsets 0 to 3), not `x^{2}!`.
`comment-discarded` is the exception: because the comment is precisely what
was stripped before tokenization, its span is in **original-input**
coordinates. `recovered` spans are a best-effort original-input range (equal
to normalized coordinates for the comment-free trailing noise that recovery
handles). Per the ratified spec, spans are informational; policy should key
on `code` + `detail`.

</MemberCard>

## Numerics

<MemberCard>

### ExactNumericValueData {#exactnumericvaluedata}

```ts
type ExactNumericValueData = {
  rational: Rational;
  radical: number;
  imRational: Rational;
  imRadical: number;
};
```

The value is equal to `rational * sqrt(radical) + imRational * sqrt(imRadical) * i`

Representable set (enforced by `ExactNumericValue`): one radical times a
Gaussian rational, `√r·(p + q·i)`:
- real values: `rational * sqrt(radical)` (imaginary part 0);
- pure-imaginary values: the real part is 0 (e.g. `√2·i`);
- both parts non-zero: `radical` and `imRadical` are equal (e.g. `2+3i`,
  `1/2-5i/3`, `√2 + √2·i`).

A value needing two different radicals on a non-zero real AND a non-zero
imaginary component (e.g. `1 + √2·i`) is NOT representable exactly.

</MemberCard>

<MemberCard>

### NumericValueData {#numericvaluedata}

```ts
type NumericValueData = {
  re: BigDecimal | number;
  im: BigDecimal | number;
};
```

</MemberCard>

<MemberCard>

### NumericValueFactory {#numericvaluefactory}

```ts
type NumericValueFactory = (data) => NumericValue;
```

</MemberCard>

### `abstract` NumericValue {#abstract-numericvalue}

<MemberCard>

##### new NumericValue()

```ts
new NumericValue(): NumericValue
```

</MemberCard>

<MemberCard>

##### NumericValue.im {#im-1}

```ts
im: number;
```

The imaginary part of this numeric value, as the double nearest to it.

Can be negative, zero or positive.

This is a PROJECTION for computations in doubles. It is `0` when the
true imaginary part is too small for a double (`10^{-800}`) and
`±Infinity` when it is too large (`10^{800}`). So do not use it to decide
whether the value is complex (use `isComplex`), nor whether the
imaginary part is finite or an integer.

</MemberCard>

<MemberCard>

##### NumericValue.type {#type-2}

</MemberCard>

<MemberCard>

##### NumericValue.isExact {#isexact}

True if numeric value is the product of a rational and the square root of an integer.

This includes: 3/4√5, -2, √2, etc...

But it doesn't include 0.5, 3.141592, etc...

</MemberCard>

<MemberCard>

##### NumericValue.asExact {#asexact}

If `isExact()`, returns an ExactNumericValue, otherwise returns undefined.

</MemberCard>

<MemberCard>

##### NumericValue.re {#re-1}

The real part of this numeric value.

Can be negative, 0 or positive.

</MemberCard>

<MemberCard>

##### NumericValue.bignumRe {#bignumre}

bignum version of .re, if available

</MemberCard>

<MemberCard>

##### NumericValue.isComplex {#iscomplex}

True if the imaginary part of this numeric value is not zero.

This is read from a representation that holds the imaginary part without
loss (the exact rational of an `ExactNumericValue`), so it is true for an
imaginary part whose double projection `im` is `0`, such as the exact
`10^{-800}·i`. Use it, not `im !== 0`, to decide whether a value is
complex.

A value with a NaN imaginary part is NaN; do not rely on `isComplex` to
detect it.

</MemberCard>

<MemberCard>

##### NumericValue.bignumIm {#bignumim}

</MemberCard>

<MemberCard>

##### NumericValue.numerator {#numerator}

</MemberCard>

<MemberCard>

##### NumericValue.denominator {#denominator}

</MemberCard>

<MemberCard>

##### NumericValue.isNaN {#isnan}

</MemberCard>

<MemberCard>

##### NumericValue.isPositiveInfinity {#ispositiveinfinity}

</MemberCard>

<MemberCard>

##### NumericValue.isNegativeInfinity {#isnegativeinfinity}

</MemberCard>

<MemberCard>

##### NumericValue.isComplexInfinity {#iscomplexinfinity}

</MemberCard>

<MemberCard>

##### NumericValue.isZero {#iszero}

</MemberCard>

<MemberCard>

##### NumericValue.isOne {#isone}

</MemberCard>

<MemberCard>

##### NumericValue.isNegativeOne {#isnegativeone}

</MemberCard>

<MemberCard>

##### NumericValue.bignumReAt() {#bignumreat}

```ts
bignumReAt(_prec): BigDecimal | undefined
```

`bignumRe` computed at `prec` significant digits instead of
`BigDecimal.precision`. Only an exact value computes its big decimal
(a quotient or a radical); the other values hold it.

####### \_prec

`number`

</MemberCard>

<MemberCard>

##### NumericValue.bignumImAt() {#bignumimat}

```ts
bignumImAt(_prec): BigDecimal | undefined
```

`bignumIm` computed at `prec` significant digits (see `bignumReAt`).

####### \_prec

`number`

</MemberCard>

<MemberCard>

##### NumericValue.isZeroWithTolerance() {#iszerowithtolerance}

```ts
isZeroWithTolerance(_tolerance): boolean
```

####### \_tolerance

`number` \| `BigDecimal`

</MemberCard>

<MemberCard>

##### NumericValue.sgn() {#sgn}

```ts
abstract sgn(): 0 | 1 | -1 | undefined
```

The sign of complex numbers is undefined

</MemberCard>

<MemberCard>

##### NumericValue.N() {#n}

```ts
abstract N(prec?): NumericValue
```

Return a non-exact representation of the numeric value.

The methods that round or bound a result (`N`, `inv`, `add`, `sub`,
`mul`, `div`, `pow`, `root`, `sqrt`, `abs`, `ln`, `exp`) take an
optional last argument `prec`, the number of significant digits of the
working precision. An engine passes its own precision; the default is
`BigDecimal.precision`, which no engine writes (50 unless the host sets
it).

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.roundToPrecision() {#roundtoprecision}

```ts
roundToPrecision(_digits): NumericValue
```

This value with each part rounded to `digits` significant digits. A
value that is already within `digits` (an exact value, a machine float,
a big decimal with no more digits) is returned as it is.

The `add` and `mul` of a big decimal are exact, so a running sum or
product of big floats grows a digit count of the size of the exponent
span, or of the number of factors: the numeric folds of `Sum` and
`Product` round each partial result with this method.

####### \_digits

`number`

</MemberCard>

<MemberCard>

##### NumericValue.neg() {#neg}

```ts
abstract neg(): NumericValue
```

</MemberCard>

<MemberCard>

##### NumericValue.inv() {#inv}

```ts
abstract inv(prec?): NumericValue
```

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.add() {#add}

```ts
abstract add(other, prec?): NumericValue
```

####### other

`number` \| [`NumericValue`](#abstract-numericvalue)

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.sub() {#sub}

```ts
abstract sub(other, prec?): NumericValue
```

####### other

[`NumericValue`](#abstract-numericvalue)

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.mul() {#mul}

```ts
abstract mul(other, prec?): NumericValue
```

####### other

`number` \| `BigDecimal` \| [`NumericValue`](#abstract-numericvalue)

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.div() {#div}

```ts
abstract div(other, prec?): NumericValue
```

####### other

`number` \| [`NumericValue`](#abstract-numericvalue)

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.pow() {#pow}

```ts
abstract pow(n, prec?): NumericValue
```

####### n

  \| `number`
  \| [`NumericValue`](#abstract-numericvalue)
  \| \{
  `re`: `number`;
  `im`: `number`;
 \}

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.root() {#root}

```ts
abstract root(n, prec?): NumericValue
```

####### n

`number`

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.sqrt() {#sqrt}

```ts
abstract sqrt(prec?): NumericValue
```

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.gcd() {#gcd}

```ts
abstract gcd(other): NumericValue
```

####### other

[`NumericValue`](#abstract-numericvalue)

</MemberCard>

<MemberCard>

##### NumericValue.abs() {#abs}

```ts
abstract abs(prec?): NumericValue
```

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.ln() {#ln}

```ts
abstract ln(base?, prec?): NumericValue
```

####### base?

`number`

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.exp() {#exp}

```ts
abstract exp(prec?): NumericValue
```

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.floor() {#floor}

```ts
abstract floor(): NumericValue
```

</MemberCard>

<MemberCard>

##### NumericValue.ceil() {#ceil}

```ts
abstract ceil(): NumericValue
```

</MemberCard>

<MemberCard>

##### NumericValue.round() {#round}

```ts
abstract round(): NumericValue
```

</MemberCard>

<MemberCard>

##### NumericValue.eq() {#eq}

```ts
abstract eq(other, prec?): boolean
```

####### other

`number` \| [`NumericValue`](#abstract-numericvalue)

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.lt() {#lt}

```ts
abstract lt(other, prec?): boolean | undefined
```

####### other

`number` \| [`NumericValue`](#abstract-numericvalue)

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.lte() {#lte}

```ts
abstract lte(other, prec?): boolean | undefined
```

####### other

`number` \| [`NumericValue`](#abstract-numericvalue)

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.gt() {#gt}

```ts
abstract gt(other, prec?): boolean | undefined
```

####### other

`number` \| [`NumericValue`](#abstract-numericvalue)

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.gte() {#gte}

```ts
abstract gte(other, prec?): boolean | undefined
```

####### other

`number` \| [`NumericValue`](#abstract-numericvalue)

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.valueOf() {#valueof-1}

```ts
valueOf(prec?): string | number
```

Object.valueOf(): returns a primitive value, preferably a JavaScript
 number over a string, even if at the expense of precision. A complex
 value is a string with `prec` significant digits in each part. Without
 `prec`, it uses `BigDecimal.precision`, not the precision of an
 engine.

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.\[toPrimitive\]() {#toprimitive-1}

```ts
toPrimitive: string | number | null
```

Object.toPrimitive(). It uses `BigDecimal.precision`, not the
precision of an engine.

####### hint

`"string"` \| `"number"` \| `"default"`

</MemberCard>

<MemberCard>

##### NumericValue.toJSON() {#tojson-1}

```ts
toJSON(): unknown
```

Object.toJSON. It uses `BigDecimal.precision`, not the precision of
an engine.

</MemberCard>

<MemberCard>

##### NumericValue.toString() {#tostring-1}

```ts
abstract toString(prec?): string
```

A string of the value. A big decimal value is rounded to `prec`
significant digits (default `BigDecimal.precision`).

####### prec?

`number`

</MemberCard>

<MemberCard>

##### NumericValue.print() {#print}

```ts
print(): void
```

Print the value to the console. It uses `BigDecimal.precision`, not
the precision of an engine.

</MemberCard>

<MemberCard>

### SmallInteger {#smallinteger}

```ts
type SmallInteger = IsInteger<number>;
```

A `SmallInteger` is an integer < 1e6

</MemberCard>

<MemberCard>

### Rational {#rational-1}

```ts
type Rational = 
  | [SmallInteger, SmallInteger]
  | [bigint, bigint];
```

A rational number is a number that can be expressed as the quotient or fraction p/q of two integers,
a numerator p and a non-zero denominator q.

A rational can either be represented as a pair of small integers or
a pair of big integers.

</MemberCard>

<MemberCard>

### BigNum {#bignum}

```ts
type BigNum = BigDecimal;
```

</MemberCard>

<MemberCard>

### Sign {#sign}

```ts
type Sign = 
  | "zero"
  | "positive"
  | "negative"
  | "non-negative"
  | "non-positive"
  | "not-zero"
  | "unsigned";
```

</MemberCard>

## OEIS

### OEISSequenceInfo {#oeissequenceinfo}

Result from an OEIS lookup operation.

<MemberCard>

##### OEISSequenceInfo.id {#id-1}

```ts
id: string;
```

OEIS sequence ID (e.g., 'A000045')

</MemberCard>

<MemberCard>

##### OEISSequenceInfo.name {#name-2}

```ts
name: string;
```

Sequence name/description

</MemberCard>

<MemberCard>

##### OEISSequenceInfo.terms {#terms}

```ts
terms: number[];
```

First several terms of the sequence

</MemberCard>

<MemberCard>

##### OEISSequenceInfo.formula? {#formula}

```ts
formula?: string;
```

Formula or recurrence (if available) — the first formula line

</MemberCard>

<MemberCard>

##### OEISSequenceInfo.formulas? {#formulas}

```ts
formulas?: string[];
```

All free-text formula lines, as returned by OEIS (if available)

</MemberCard>

<MemberCard>

##### OEISSequenceInfo.comments? {#comments}

```ts
comments?: string[];
```

Comments about the sequence

</MemberCard>

<MemberCard>

##### OEISSequenceInfo.url {#url}

```ts
url: string;
```

URL to the OEIS page

</MemberCard>

### OEISOptions {#oeisoptions}

Options for OEIS operations.

<MemberCard>

##### OEISOptions.timeout? {#timeout}

```ts
timeout?: number;
```

Request timeout in milliseconds (default: 10000)

</MemberCard>

<MemberCard>

##### OEISOptions.maxResults? {#maxresults}

```ts
maxResults?: number;
```

Maximum number of results to return for lookups (default: 5)

</MemberCard>

### OEISCandidate {#oeiscandidate}

An OEIS-attributed closed-form proposal produced by `ce.interpret()`.

The `expression` has been *verified* to reproduce every extracted sample
exactly. Attribution (`id`, `name`, `url`, `formula`) is mandatory: OEIS data
is CC BY-NC, so a candidate must always carry a link back to its source.

<MemberCard>

##### OEISCandidate.expression {#expression}

```ts
expression: Expression;
```

The parsed and sample-verified closed-form expression.

</MemberCard>

<MemberCard>

##### OEISCandidate.id {#id-2}

```ts
id: string;
```

OEIS sequence ID (e.g., 'A000217').

</MemberCard>

<MemberCard>

##### OEISCandidate.name {#name-3}

```ts
name: string;
```

Sequence name/description.

</MemberCard>

<MemberCard>

##### OEISCandidate.url {#url-1}

```ts
url: string;
```

URL to the OEIS page.

</MemberCard>

<MemberCard>

##### OEISCandidate.formula {#formula-1}

```ts
formula: string;
```

The free-text OEIS formula line the expression was parsed from.

</MemberCard>

### InterpretResult {#interpretresult}

Result of `ce.interpret()`: the sync-recognized form of the input (the same
value the `Interpret` head returns), plus any OEIS-attributed candidates.

<MemberCard>

##### InterpretResult.expression {#expression-1}

```ts
expression: Expression;
```

The recognized expression, or the input unchanged when nothing fired.

</MemberCard>

<MemberCard>

##### InterpretResult.candidates {#candidates}

```ts
candidates: OEISCandidate[];
```

Verified, OEIS-attributed closed-form proposals (possibly empty).

</MemberCard>

## Other

### FunctionPropertyRecord {#functionpropertyrecord}

A single analytic-property record for an operator. The MathJSON fields are
raw (as translated from Fungrim); box them with `ce.expr` to query.

<MemberCard>

##### FunctionPropertyRecord.id {#id}

```ts
readonly id: string;
```

The Fungrim entry id (provenance).

</MemberCard>

<MemberCard>

##### FunctionPropertyRecord.property {#property}

```ts
readonly property: string;
```

One of `Poles`, `Zeros`, `BranchPoints`, `BranchCuts`, `Residue`,
`EssentialSingularities`, `IsHolomorphic`, `IsMeromorphic`,
`AnalyticContinuation`, `Solutions`, `ComplexZeroMultiplicity`.

</MemberCard>

<MemberCard>

##### FunctionPropertyRecord.var {#var}

```ts
readonly var: string | null;
```

The distinguished variable the property is stated in (e.g. `z`).

</MemberCard>

<MemberCard>

##### FunctionPropertyRecord.argIndex {#argindex}

```ts
readonly argIndex: number | null;
```

Index of `var` among the operator's arguments, or null when there is no
single argument position (parametric / composite).

</MemberCard>

<MemberCard>

##### FunctionPropertyRecord.expr {#expr}

```ts
readonly expr: ExpressionInput | null;
```

</MemberCard>

<MemberCard>

##### FunctionPropertyRecord.domain {#domain}

```ts
readonly domain: ExpressionInput | null;
```

</MemberCard>

<MemberCard>

##### FunctionPropertyRecord.point {#point}

```ts
readonly point: ExpressionInput | null;
```

</MemberCard>

<MemberCard>

##### FunctionPropertyRecord.condition {#condition}

```ts
readonly condition: ExpressionInput | null;
```

</MemberCard>

<MemberCard>

##### FunctionPropertyRecord.value {#value}

```ts
readonly value: ExpressionInput | null;
```

</MemberCard>

<MemberCard>

##### FunctionPropertyRecord.assumptions {#assumptions}

```ts
readonly assumptions: ExpressionInput | null;
```

</MemberCard>

### FunctionProperties {#functionproperties}

Queryable analytic properties of an operator, returned by
`ce.functionProperties(name)`. The set-valued accessors return a boxed set
(e.g. `NonPositiveIntegers`) for the unconditional record of that kind, or
`undefined` when no such record exists. Parametric / conditional records
(e.g. residues that depend on parameters) are available via `entries`.

<MemberCard>

##### FunctionProperties.operator {#operator}

```ts
readonly operator: string;
```

</MemberCard>

<MemberCard>

##### FunctionProperties.entries {#entries}

```ts
readonly entries: readonly FunctionPropertyRecord[];
```

All analytic-property records for this operator.

</MemberCard>

<MemberCard>

##### FunctionProperties.poles {#poles}

```ts
readonly poles: Expression | undefined;
```

</MemberCard>

<MemberCard>

##### FunctionProperties.zeros {#zeros}

```ts
readonly zeros: Expression | undefined;
```

</MemberCard>

<MemberCard>

##### FunctionProperties.branchPoints {#branchpoints}

```ts
readonly branchPoints: Expression | undefined;
```

</MemberCard>

<MemberCard>

##### FunctionProperties.branchCuts {#branchcuts}

```ts
readonly branchCuts: Expression | undefined;
```

</MemberCard>

<MemberCard>

##### FunctionProperties.essentialSingularities {#essentialsingularities}

```ts
readonly essentialSingularities: Expression | undefined;
```

</MemberCard>

<MemberCard>

##### FunctionProperties.holomorphicDomain {#holomorphicdomain}

```ts
readonly holomorphicDomain: Expression | undefined;
```

The domain on which the function is holomorphic.

</MemberCard>

<MemberCard>

##### FunctionProperties.isMeromorphic {#ismeromorphic}

```ts
readonly isMeromorphic: boolean | undefined;
```

Whether the function is meromorphic, when the corpus records it.

</MemberCard>

<MemberCard>

### SymbolTable {#symboltable}

```ts
type SymbolTable = {
  parent: SymbolTable | null;
  ids: {};
};
```

</MemberCard>

<MemberCard>

### newSymbolIds() {#newsymbolids}

```ts
function newSymbolIds(): {}
```

A prototype-free [SymbolTable.ids](#symboltable) map — see the note there.

</MemberCard>

<MemberCard>

### ApplicationContext {#applicationcontext}

```ts
type ApplicationContext = {
  head: MathJsonSymbol;
  arguments: ReadonlyArray<MathJsonExpression>;
  sourceOffsets: readonly [number, number];
  headSourceOffsets: readonly [number, number];
  ancestors: ReadonlyArray<{
     operator: MathJsonSymbol;
     operandIndex: number;
    }>;
};
```

A syntactically ambiguous symbol followed by parentheses.

The arguments and ancestry describe the parsed structure, not LaTeX tokens.
Source offsets are half-open UTF-16 offsets in normalized LaTeX, as for parse
diagnostics. Ancestry runs from the outermost expression to the nearest
parent, with one-based operand indices; it includes written Delimiters.

</MemberCard>

<MemberCard>

### ContourOrientation {#contourorientation}

```ts
type ContourOrientation = "counterclockwise" | "clockwise";
```

Positive orientation is counterclockwise.

</MemberCard>

<MemberCard>

### Contour {#contour}

```ts
type Contour = 
  | {
  kind: "real-line";
  principalValue: boolean;
 }
  | {
  kind: "circle";
  center: ExpressionInput;
  radius: ExpressionInput;
  orientation: ContourOrientation;
 }
  | {
  kind: "polygon";
  vertices: readonly ExpressionInput[];
  orientation: ContourOrientation;
 }
  | {
  kind: "rectangle";
  lowerLeft: ExpressionInput;
  upperRight: ExpressionInput;
  orientation: ContourOrientation;
};
```

A closed contour, or a real line completed by a controlled semicircle.
Polygon vertices are complex numbers in traversal order. An explicit
polygon orientation overrides that order.

#### Type Declaration

\{
  `kind`: `"real-line"`;
  `principalValue`: `boolean`;
 \}

#### Contour.kind

```ts
kind: "real-line";
```

The real axis from -infinity to +infinity, closed in a half-plane
after the large-arc contribution has been established.

\{
  `kind`: `"circle"`;
  `center`: [`ExpressionInput`](#expressioninput);
  `radius`: [`ExpressionInput`](#expressioninput);
  `orientation`: [`ContourOrientation`](#contourorientation);
 \}

\{
  `kind`: `"polygon"`;
  `vertices`: readonly [`ExpressionInput`](#expressioninput)[];
  `orientation`: [`ContourOrientation`](#contourorientation);
 \}

\{
  `kind`: `"rectangle"`;
  `lowerLeft`: [`ExpressionInput`](#expressioninput);
  `upperRight`: [`ExpressionInput`](#expressioninput);
  `orientation`: [`ContourOrientation`](#contourorientation);
 \}

</MemberCard>

<MemberCard>

### ContourInput {#contourinput}

```ts
type ContourInput = Contour | ExpressionInput;
```

Accepted MathJSON forms are CircleContour(center, radius, orientation?),
PolygonContour(List(vertices...), orientation?), and
RectangleContour(lowerLeft, upperRight, orientation?), and
RealLineContour(principalValue?). The orientation is +1 (counterclockwise)
or -1 (clockwise); principalValue is True or False. Circle equations
Equal(Abs(z - center), radius) are also accepted.

</MemberCard>

<MemberCard>

### NormalizedContour {#normalizedcontour}

```ts
type NormalizedContour = 
  | {
  kind: "real-line";
  principalValue: boolean;
  orientation: ContourOrientation;
 }
  | {
  kind: "circle";
  center: Expression;
  radius: Expression;
  orientation: ContourOrientation;
 }
  | {
  kind: "polygon";
  vertices: readonly Expression[];
  orientation: ContourOrientation;
};
```

</MemberCard>

<MemberCard>

### ContourPole {#contourpole}

```ts
type ContourPole = {
  point: Expression;
  kind: "pole" | "essential" | "removable" | "undetermined";
  location: "inside" | "outside" | "boundary" | "undetermined";
  enclosed: boolean | undefined;
  order: number;
  residue: Expression;
  leadingCoefficient: Expression;
};
```

</MemberCard>

<MemberCard>

### ContourIntegralResult {#contourintegralresult}

```ts
type ContourIntegralResult = {
  method: "residue-theorem";
  status:   | "success"
     | "pole-on-contour"
     | "invalid-contour"
     | "unsupported"
     | "undetermined";
  reason: string;
  contour: NormalizedContour;
  polesComplete: boolean;
  poleScope: "global" | "contour";
  poles: readonly ContourPole[];
  divergence: "positive-infinity" | "negative-infinity" | "no-value" | "undetermined";
  residueSum: Expression;
  value: Expression;
  realIntegral: {
     closure: "upper" | "lower";
     projection: "none" | "real" | "imaginary";
     principalValue: boolean;
     largeArcContribution: Expression;
    };
};
```

Intermediate results of symbolic contour integration. No partial sum is
exposed as an integral: value and residueSum exist only on success.
poles includes essential singularities and removable denominator zeros,
explicitly marked as such. The pole-on-contour status also covers an
essential singularity on the integration path.
polesComplete means candidate discovery is complete in poleScope, not that every
candidate's order or residue has been determined.

</MemberCard>

<MemberCard>

### OperatorDefinition {#operatordefinition}

```ts
type OperatorDefinition = Partial<BaseDefinition> & Partial<OperatorDefinitionFlags> & {
  type: OperatorTypeHandlerOnTypes;
  signature:   | Type
     | TypeString
     | BoxedType;
  parameters:   | Readonly<Record<string, ParameterDocumentation>>
     | ReadonlyArray<ParameterDocumentation>;
  inferredSignature: boolean;
  sgn: (ops, options) => Sign | undefined;
  isPositive: boolean;
  isNonNegative: boolean;
  isNegative: boolean;
  isNonPositive: boolean;
  even: (ops, options) => boolean | undefined;
  complexity: number;
  canonical: (ops, options) => Expression | null;
  evaluate:   | ((ops, options) => Expression | undefined)
     | Expression;
  evaluateAsync: (ops, options) => Promise<Expression | undefined>;
  evaluateMod: EvaluateModHandler;
  evalDimension: (args, options) => Expression;
  derivative: OperatorDerivative;
  compile: OperatorCompileHandler;
  eq: (a, b, prover?) => boolean | undefined;
  neq: (a, b) => boolean | undefined;
  collection: CollectionHandlers;
  arithmetic: ArithmeticDefinition;
  canEnumerate: (expr) => boolean | undefined;
  elementCount: (expr) => number | undefined;
  elementAt: (expr, index) => Expression | undefined;
  inferOperandTypes: (ops, requirement) => 
     | ReadonlyArray<
     | Type
     | {
     replace: Type;
    }
     | undefined>
     | undefined;
};
```

#### OperatorDefinition.type?

```ts
type?: OperatorTypeHandlerOnTypes;
```

The type of the result (return type) as a function of the operand
DESCRIPTORS — their types, facts and structure, never the operand
expressions. See [OperatorTypeHandlerOnTypes](#operatortypehandlerontypes).

Should be a subtype of the type indicated by the signature: for a
signature `(number) -> real` the result may be `real` or `integer`,
never `complex`.

#### OperatorDefinition.signature?

```ts
signature?: 
  | Type
  | TypeString
  | BoxedType;
```

The function signature, describing the type of the arguments and the
return type.

If a `type` handler is provided, the return type of the function should
be a subtype of the return type in the signature.

**Default values.** An optional parameter can have a default value,
written after its type: `(x: number, factor: number = 2) -> number`.
A parameter with a default is optional (it is not also marked `?`).
The parameters with a default come after the required parameters and
before the optional parameters without a default.

A default is a number (a finite number, `NaN`, `+oo` or `-oo`), a
string, `true` or `false`, a symbol, the empty list `[]` or the empty
dictionary `{}`. A symbol default is the symbol itself, not its value
when the operator is declared: `over: set = Integers`,
`mode: symbol<Auto> | symbol<Manual> = Auto`. The symbol need not be
declared. For another value, declare a constant and give its name.

When the operator is declared, each default is checked against the
type of its parameter, and the declaration throws if it does not fit:
a number, a string, a boolean, `[]` or `{}` must match the type, a
declared symbol must be a valid argument at that parameter, and for a
parameter typed with literal symbol types the symbol must be one of
them. A default is refused in an overloaded signature (an intersection
of signatures), on a parameter whose type mentions a type variable, and
anywhere other than the parameters of the top-level signature (for
example in the type of a parameter that is itself a function).

A call that leaves out a parameter with a default receives the default
when it is canonicalized: `Scaled(3)` is the same expression as
`Scaled(3, 2)`, and the `evaluate` handler, the `type` handler and the
compiler see two operands. The default is inserted only when every
required parameter has an argument. The signature prints the default.

#### OperatorDefinition.parameters?

```ts
parameters?: 
  | Readonly<Record<string, ParameterDocumentation>>
| ReadonlyArray<ParameterDocumentation>;
```

The documentation of the parameters, keyed by the parameter names of
the `signature`, so that the arms of an overload set share it. A
string is the description of the parameter alone. The editor
services show it in the signature help and in the completion of a
named argument (`epsilSignatureHelp()`, `epsilCompletions()`).

A list documents the parameters by position instead, for a signature
whose parameters have no name (`(complex | quantity) -> number`): the
entry `i` documents the parameter `i` of each arm of the signature. An
empty string leaves a parameter undocumented.

```js
parameters: [{ description: 'The angle, in radians.', sample: 'pi / 4' }]
```

```js
parameters: {
  count: { description: 'The number of elements to keep.', sample: '2' },
  options: {
    description: 'The options of the plot.',
    keys: { x: { type: 'tuple<real, real>', description: 'The x range.', sample: '(-5, 5)' } },
  },
}
```

#### OperatorDefinition.inferredSignature?

```ts
inferredSignature?: boolean;
```

If `true`, the `signature` is a starting point to be refined, not a
contract: assigning a function literal to this operator narrows the
signature from the literal's body, and calls type from the narrowed
signature.

Declaring a `signature` normally pins it (`inferredSignature: false`),
which is what you want for a fixed API. Set this to `true` to vouch
that a name is an operator — so `f(x)` parses as an application rather
than a multiplication — while leaving its types to be inferred from the
body assigned later:

```js
ce.declare('q', { signature: '(unknown) -> unknown', inferredSignature: true });
ce.assign('q', ce.parse('t \\mapsto 2t+1'));
// signature is now `(unknown) -> number`, so `q(x) < y` types
// `boolean` and compiles, while `q(L) < y` over a list `L` still types
// `list<boolean>` and fails closed.
```

A declaration that omits `signature` entirely behaves the same way.

#### OperatorDefinition.sgn?

```ts
sgn?: (ops, options) => Sign | undefined;
```

Return the sign of the function expression.

If the sign cannot be determined, return `undefined`.

When determining the sign, only literal values and the values of
symbols, if they are literals, should be considered.

Do not evaluate the arguments.

However, the type and sign of the arguments can be used to determine the
sign.

The handler must be a pure function of the operands — the type path
dispatches it while deriving an application's type. See the purity
contract on `OperatorDefinition.sgn`.

#### OperatorDefinition.isPositive?

```ts
readonly isPositive?: boolean;
```

The value of this expression is > 0, same as `isGreater(0)`

#### OperatorDefinition.isNonNegative?

```ts
readonly isNonNegative?: boolean;
```

The value of this expression is >= 0, same as `isGreaterEqual(0)`

#### OperatorDefinition.isNegative?

```ts
readonly isNegative?: boolean;
```

The value of this expression is &lt; 0, same as `isLess(0)`

#### OperatorDefinition.isNonPositive?

```ts
readonly isNonPositive?: boolean;
```

The  value of this expression is &lt;= 0, same as `isLessEqual(0)`

#### OperatorDefinition.even?

```ts
even?: (ops, options) => boolean | undefined;
```

Return `true` if the function expression is even, `false` if it is odd
and `undefined` if it is neither (for example if it is not a number,
or if it is a complex number).

#### OperatorDefinition.complexity?

```ts
complexity?: number;
```

A number used to order arguments.

Argument with higher complexity are placed after arguments with
lower complexity when ordered canonically in commutative functions.

- Additive functions: 1000-1999
- Multiplicative functions: 2000-2999
- Root and power functions: 3000-3999
- Log functions: 4000-4999
- Trigonometric functions: 5000-5999
- Hypertrigonometric functions: 6000-6999
- Special functions (factorial, Gamma, ...): 7000-7999
- Collections: 8000-8999
- Inert and styling:  9000-9999
- Logic: 10000-10999
- Relational: 11000-11999

**Default**: 100,000

#### OperatorDefinition.canonical?

```ts
canonical?: (ops, options) => Expression | null;
```

Return the canonical form of the expression with the arguments `args`.

The arguments (`args`) may not be in canonical form. If necessary, they
can be put in canonical form.

This handler should validate the type and number of the arguments
(arity).

If a required argument is missing, it should be indicated with a
`["Error", "'missing"]` expression. If more arguments than expected
are present, this should be indicated with an
`["Error", "'unexpected-argument'"]` error expression

If the type of an argument is not compatible, it should be indicated
with an `incompatible-type` error.

`["Sequence"]` expressions are not folded and need to be handled
 explicitly.

If the function is associative, idempotent or an involution,
this handler should account for it. Notably, if it is commutative, the
arguments should be sorted in canonical order.

Values of symbols should not be substituted, unless they have
a `holdUntil` attribute of `"never"`.

The handler should not consider the value or any assumptions about any
of the arguments that are symbols or functions (i.e. `arg.is(0)`,
`arg.isInteger`, etc...) since those may change over time.

The result of the handler should be a canonical expression.

If the arguments do not match, they should be replaced with an
appropriate `["Error"]` expression. If the expression cannot be put in
canonical form, the handler should return `null`.

#### OperatorDefinition.evaluate?

```ts
evaluate?: 
  | ((ops, options) => Expression | undefined)
  | Expression;
```

Evaluate a function expression.

When the handler is invoked, the arguments have been evaluated, except
if the `lazy` option is set to `true`.

It is not necessary to further simplify or evaluate the arguments.

A function of the host (a handler that is a JavaScript function, of a
definition that is not `lazy`) receives a `List` for an argument that
evaluates to a finite lazy indexed collection: `f(1..3)` receives
`List(1, 2, 3)`, not `Range(1, 3, 1)`, and `f(map(x => 2x, [1, 2]))`
receives `List(2, 4)`, with the callback called for each element
before the handler. Compiled JavaScript passes the same `List`. An
endless collection, one whose count is not known, one of more than
`ce.maxCollectionSize` elements, a set, a dictionary and a view with
an effect whose count is not known without a call that has an effect
(`Tabulate(f, g())` where `f` and `g` have an effect) are passed as
they are. A handler that needs the collection as written (to read the
bounds of a `Range`, or to read only some elements) declares the
function `lazy: true` and evaluates the operand itself.

If performing numerical calculations and `options.numericalApproximation`
is `false` return an exact numeric value, for example return a rational
number or a square root, rather than a floating point approximation.
Use `ce.number()` to create the numeric value.

If the expression cannot be evaluated, due to the values, types, or
assumptions about its arguments, return `undefined` or
an `["Error"]` expression.

The handler must not evaluate an expression that contains the call
that it evaluates, for example an expression that the host code keeps
in a variable. The engine does not detect this, and the result is not
specified. Under `evaluateAsync()` the promise of the outer evaluation
can never settle (see `evaluateAsync`).

#### OperatorDefinition.evaluateAsync?

```ts
evaluateAsync?: (ops, options) => Promise<Expression | undefined>;
```

An asynchronous version of `evaluate`.

A handler that evaluates an operand with `evaluateAsync` passes its
own `options` on (`x.evaluateAsync(options)`, or a copy that keeps the
`_effects`, `_contextStack` and `_precisionWindow` fields): they carry
the state of the evaluation across the handler's `await`s, among which
the precision window of an enclosing `N(x, p)` call. An operand
evaluation started with options of the handler's own inherits the
window in force when it starts, but a handler that awaits BEFORE it
evaluates its operand starts that evaluation outside the window.

The handler must not evaluate an expression that contains the call
that it evaluates. If it does, the promise of the outer evaluation can
never settle. For example, with `g` a host operator whose handler is
`async () => { await node.evaluateAsync(); return ce.number(5); }`
and `node` the expression `Reverse(List(1, g()))`, the call
`node.evaluateAsync()` never settles. When `g` is declared `pure`, the
nested call waits for the evaluation of `node` that is in progress,
and that evaluation waits for the handler. Otherwise, each nested call
starts a new evaluation of `node`, which calls the handler again,
without end. The engine does not detect either case.

#### OperatorDefinition.evaluateMod?

```ts
evaluateMod?: EvaluateModHandler;
```

The residue of an application of this operator modulo an integer,
computed without forming its value.

`Mod(x, m)` calls it, before `x` is evaluated, when `m` is an exact
integer `>= 2`, the call is not under `.N()` and the operator of `x`
has the handler; `PowerMod(a, e, m)` calls it for its base `a`. The
residue it returns, in `[0, m)`, is the answer. `Mod(x, n, d)` reaches
it through `Mod(x - d, n)`. When the handler returns `undefined`, or
the operator has none, `x` is evaluated and reduced as usual, so the
handler must agree with `evaluate`: `Mod(x, m)` has the same value
with and without it.

- `ops` are the operands of the application, canonical and **not
  evaluated**. The handler evaluates only what it needs exactly (the
  index of `Fibonacci`) and reduces the others with `context.mod`.
- `modulus` is `>= 2`.
- `context.mod(x)` is the residue of an operand, through its own
  handler when it has one, so that handlers nest:
  `Mod(2 * Fibonacci(10^9) + 1, p)`. It never evaluates an operand
  that has a handler.

Only an operator whose value is always an integer should have one: a
quotient or a rational literal has none, and `Mod(1/3, 7)` stays `1/3`.
`Add`, `Multiply`, `Negate`, `Subtract` and `Power` (with an exact
positive integer exponent) have one.

The handler is read by the interpreter only. Compiled code does not use
it.

```ts
ce.declare('Huge', {
  signature: '(integer) -> integer',
  evaluateMod: ([n], m) => ...,
});
```

#### OperatorDefinition.evalDimension?

```ts
evalDimension?: (args, options) => Expression;
```

**`Experimental`**

Dimensional analysis

#### OperatorDefinition.derivative?

```ts
derivative?: OperatorDerivative;
```

The partial derivatives of this operator, used by `D`, `Derivative`
and the prime notation (`f'(x)`). See [OperatorDerivative](#operatorderivative) for
the two accepted forms.

Without this key, the derivative of an application of an operator
whose `evaluate` handler does not give a formula stays symbolic:
`D(Sq(x), x)` is `Apply(Derivative(Sq, 1), x)`. With it, the
derivative is computed with the chain rule:

```ts
ce.declare('Sq', {
  signature: '(number) -> number',
  evaluate: ([x]) => (isNumber(x) ? x.mul(x) : undefined),
  derivative: [['Function', ['Multiply', 2, 'x'], 'x']],
});
ce.parse('\\frac{d}{dx} \\operatorname{Sq}(x^2)').evaluate();
// ➔ 4x^3   (that is, Sq'(x^2) · 2x = 2x^2 · 2x)
```

When the definition also has an `evaluate` handler that is a function
literal, this key has precedence: the derivative is computed from
this key, not by differentiating the body of the literal.

An operator of the standard library keeps its own derivative rule. A
definition that shadows a standard library name (a user definition
of `Sinh`, for example) is a different operator, and its `derivative`
key is used.

#### OperatorDefinition.compile?

```ts
compile?: OperatorCompileHandler;
```

A compilation handler for this operator: it gives an expression that
`compile()` compiles in place of a call of this operator, or
`undefined` to keep the library's compilation of the operator. See
[OperatorCompileHandler](#operatorcompilehandler).

The handler is not asked about the structural and control-flow heads,
which have their own lowering: `Sequence`, `Sum`, `Product`,
`Function`, `Declare`, `Assign`, `Return`, `Break`, `Continue`,
`Loop`, `Comprehension`, `If`, `Match`, `Block`. `Which` is the
exception: its handler is asked.

To change how an operator of the engine compiles and keep its
evaluation, attach the handler to the definition that
`ce.lookupDefinition()` returns. A re-declaration of the operator
replaces its `evaluate` and `canonical` handlers and its effects.

```ts
const def = ce.lookupDefinition('Which');
if (def && 'operator' in def) def.operator.compile = myWhichHandler;
```

The handler is attached to the definition of one engine.

#### OperatorDefinition.eq?

```ts
eq?: (a, b, prover?) => boolean | undefined;
```

Custom equality handler.

`prover` indicates the tier of the caller: `false` for the cheap
arithmetic tier (`eq()` / `.isEqual()`), `true` for the prover tier
(`eqIdentical()` / `.isIdenticallyEqual()`), and `undefined` when the
caller does not distinguish (e.g. `cmp()`). A handler that does
prover-tier work (sampling, expand/simplify, identity questions in the
free variables) must decline — return `undefined` — when
`prover === false`.

#### OperatorDefinition.arithmetic?

```ts
arithmetic?: ArithmeticDefinition;
```

Declares that the values this operator constructs are a VALUE KIND:
values with their own arithmetic (a residue class, a measurement, an
element of a finite field). See [ArithmeticDefinition](#arithmeticdefinition).

The result type of every arm of the signature must be a KIND TYPE: a
kind primitive (`residue`), or a nominal type whose definition is
exactly `value`, declared with
`ce.declareType(name, 'value', { mint: false })`. The marker arms
`nan`, `missing`, `nothing` and `error` may be added. Any other result
type (a number type, `boolean`, `string`, a collection, `value`,
`any`, `expression`, a nominal type with another definition) is
refused when the operator is declared. A definition that gives `add`
must also give `negate`.

The fields `admittedAs`, `resultType` and `compile.type` belong to the
kind TYPE, not to this operator: the operators of one kind type that
are declared at the same time must give equal values for them (or
leave them out).

#### OperatorDefinition.canEnumerate?

```ts
canEnumerate?: (expr) => boolean | undefined;
```

For an operator that RETURNS a collection but has no `collection`
handlers (an EAGER producer — `Characters`, `Divisors`, `Eigenvalues`,
…): can `evaluate()` produce the collection's elements in the current
state?

This is the operator's own decline test — the guard at the top of its
`evaluate` handler — exposed so the enumerability facet
(`isEnumerableCollection`) can answer without evaluating. Contract
(see `docs/COLLECTIONS-MODEL.md`):

- MUST be O(1), evaluation-free and side-effect free. An impure
  producer answers from its operands' facets, consuming no draws.
- `false` means evaluation WOULD decline — callers stay inert without
  paying for the evaluation.
- `true` is a hard promise that evaluation produces the collection. An
  operator whose success is not cheaply decidable (`Solve`,
  `FindRoot`) must return `undefined`, never `true`.
- The operand seen here is the CANONICAL operand, not the evaluated
  one. An unevaluated compound operand (`Divisors(n + 1)`) whose value
  cannot be read cheaply must yield `undefined` (undecidable), not
  `false` — only a definitively unavailable operand (a valueless
  symbol, a literal of the wrong kind) yields `false`. See
  `canEnumerateOperand` (`collection-utils.ts`) for the shared
  tri-state resolution.

Ignored (never consulted) when the definition has `collection`
handlers — those own enumerability via `collection.isEnumerable`.

#### OperatorDefinition.elementCount?

```ts
elementCount?: (expr) => number | undefined;
```

For an operator that RETURNS a collection but has no `collection`
handlers (an EAGER producer — `Sort`, `Chunk`, `Ordering`, …): how many
elements would `evaluate()` produce?

The `count` twin of canEnumerate, and the honest replacement for
the broadcast count fallback: `count` reads the operands' agreed length
only for a `broadcastable` operator, where agreement IS the semantics
(`docs/BROADCAST-MODEL.md`). A reshaping operator's length is its own
business, so it must say so here or report `undefined`.

Contract, mirroring `canEnumerate`:

- MUST be O(1), evaluation-free and side-effect free. An impure producer
  (`RandomShuffle`) answers from its operands' facets, consuming ZERO
  draws.
- The operands seen here are the CANONICAL ones. Anything not cheaply
  knowable — a non-literal shape argument, an unknown source length —
  must report `undefined` (decline), never a guess.
- A returned number is a hard promise: it must equal
  `expr.evaluate().count`. When evaluation would DECLINE (an infinite or
  unknown-length source), report `undefined` — a count nobody can walk is
  worse than no count (Tycho item-169 ruling).

Consulted only when the definition has no `collection.count` handler —
a declared `count` owns the answer, including its `undefined`.

#### OperatorDefinition.elementAt?

```ts
elementAt?: (expr, index) => Expression | undefined;
```

For an operator that RETURNS a collection but has no `collection`
handlers: the element at the 1-based position `index` of the
collection that `evaluate()` would produce, built from the operands
with no evaluation. `PointX(L)` at `k` is `PointX(L.at(k))`.

The `at()` twin of elementCount. Contract:

- Called only for a valid, pure expression whose `count` is known, with
  `1 ≤ index ≤ count`.
- MUST NOT evaluate the expression. The element it returns can be
  unevaluated, and its evaluation MUST equal
  `expr.evaluate().at(index)`: `at()` returns that evaluation.
- Anything not cheaply knowable must report `undefined` (decline):
  `at()` then evaluates the expression and reads the element of the
  result.

Consulted only when the definition has no `collection.at` handler.

#### OperatorDefinition.inferOperandTypes?

```ts
inferOperandTypes?: (ops, requirement) => 
  | ReadonlyArray<
  | Type
  | {
  replace: Type;
 }
  | undefined>
  | undefined;
```

Use-driven element inference. Called when a type REQUIREMENT reaches
an application of this operator: its result is an operand of a typed
parameter (`k(xs[1])` with `k: (integer) -> integer` requires
`integer`) or of an arithmetic operator, which requires a scalar
numeric result (`xs[1] + 1` requires `real`). The handler answers the
type each OPERAND must have for the result to satisfy the requirement:
one entry per operand, `undefined` where that operand learns nothing,
or `undefined` for the whole call to decline.

The engine writes each entry onto the operand through the ordinary
inference path, so only an operand whose type is inferred (or still
unknown) moves, a declared type never does, and an operand that is
itself an application forwards to its own operator's handler
(`m[1][2] + 1` reaches `m`). A `widen` never reaches the handler: it
carries a result possibility, not a constraint on the operands.

Only a VALUE requirement reaches the handler: never `any`, `unknown`,
`value`, `nothing`, an absence marker alone, or a function type. An
absence arm (`real | missing`) is stripped before the call.

An entry can also be `{ replace: t }`: the handler has combined the
operand's current inferred type with this requirement itself, and `t`
replaces that type instead of being intersected with it. This is for a
combination that is not an intersection, such as a tuple that gets one
more component. The same guards apply: a declared type never moves.

`At` answers `dictionary<r> | indexed_collection<r>` for its base and
`First`/`Second`/`Third`/`Last` answer `indexed_collection<r>`. The
scalar reading is written on purpose: `xs[1] + 1` requires `number`
of the element, exactly as `x + 1` infers a bare `x` as `number`.
For a base that is a bare function parameter, `At` answers a
`replace` entry that records each index read separately (a tuple for
literal indices). For a base whose type is a tuple, read at a literal
index inside the tuple, `At` answers that tuple with the one
component narrowed by `r`. Design and rulings:
`docs/INFERENCE_ROADMAP.md` §5.

</MemberCard>

<MemberCard>

### SymbolDefinitions {#symboldefinitions}

```ts
type SymbolDefinitions = Readonly<{}>;
```

</MemberCard>

### ILatexSyntax {#ilatexsyntax}

Minimal interface for a LaTeX parser/serializer.
 Structurally compatible with `LatexSyntax` without importing it.

<MemberCard>

##### ILatexSyntax.dictionary? {#dictionary-2}

```ts
readonly dictionary?: readonly Partial<OnlyFirst<
  | ExpressionEntry
  | MatchfixEntry
  | InfixEntry
  | PostfixEntry
  | PrefixEntry
  | SymbolEntry
  | FunctionEntry
  | EnvironmentEntry
  | DefaultEntry, {} & (
  | ExpressionEntry
  | MatchfixEntry
  | InfixEntry
  | PostfixEntry
  | PrefixEntry
  | SymbolEntry
  | FunctionEntry
  | EnvironmentEntry
  | DefaultEntry)>>[];
```

The dictionary entries, including the entries added with
 `addEntries()`. A call to `addEntries()` gives a new array, so a
 different array means a different dictionary. Rule strings are parsed
 with these entries plus the rule entries. Optional: a minimal injected
 syntax may not have it, and then rule strings are parsed with the
 default dictionary. See `LatexSyntax.dictionary`.

</MemberCard>

<MemberCard>

##### ILatexSyntax.parse() {#parse}

```ts
parse(latex, options?): MathJsonExpression | null
```

####### latex

`string`

####### options?

`Partial`\<[`ParseLatexOptions`](#parselatexoptions)\>

</MemberCard>

<MemberCard>

##### ILatexSyntax.serialize() {#serialize-2}

```ts
serialize(expr, options?): string
```

####### expr

[`MathJsonExpression`](#mathjsonexpression)

####### options?

`Record`\<`string`, `unknown`\>

</MemberCard>

<MemberCard>

##### ILatexSyntax.getNamedTriggers()? {#getnamedtriggers}

```ts
getNamedTriggers(): readonly {
  name: string;
  triggers: string[];
 }[]
```

Named dictionary entries with their LaTeX trigger strings, for reverse
 library search (`ce.searchDefinitions()`). Optional: MathJSON-only
 builds and minimal injected syntaxes may not implement it.

</MemberCard>

<MemberCard>

##### ILatexSyntax.addEntries()? {#addentries}

```ts
addEntries(entries): void
```

Add LaTeX dictionary entries. The next parse or serialization uses
 them. Optional: `LatexSyntax` implements it, a minimal injected syntax
 may not. If the same instance is used by several engines, the entries
 apply to all of them. See `LatexSyntax.addEntries()`.

####### entries

readonly `Partial`\<`OnlyFirst`\<
  \| [`ExpressionEntry`](#expressionentry)
  \| [`MatchfixEntry`](#matchfixentry)
  \| [`InfixEntry`](#infixentry)
  \| [`PostfixEntry`](#postfixentry)
  \| [`PrefixEntry`](#prefixentry)
  \| [`SymbolEntry`](#symbolentry)
  \| [`FunctionEntry`](#functionentry)
  \| [`EnvironmentEntry`](#environmententry)
  \| [`DefaultEntry`](#defaultentry), \{\} & (
  \| [`ExpressionEntry`](#expressionentry)
  \| [`MatchfixEntry`](#matchfixentry)
  \| [`InfixEntry`](#infixentry)
  \| [`PostfixEntry`](#postfixentry)
  \| [`PrefixEntry`](#prefixentry)
  \| [`SymbolEntry`](#symbolentry)
  \| [`FunctionEntry`](#functionentry)
  \| [`EnvironmentEntry`](#environmententry)
  \| [`DefaultEntry`](#defaultentry))\>\>[]

</MemberCard>

<MemberCard>

### OperatorInfo {#operatorinfo}

```ts
type OperatorInfo = {
  kind: "function" | "opaque";
  signature: BoxedType;
  canEvaluate: boolean;
};
```

</MemberCard>

<MemberCard>

### SymbolInfo {#symbolinfo}

```ts
type SymbolInfo = {
  kind: "constant" | "variable";
  type: BoxedType;
};
```

</MemberCard>

<MemberCard>

### DefinitionSearchResult {#definitionsearchresult}

```ts
type DefinitionSearchResult = {
  id: MathJsonSymbol;
  kind: "function" | "opaque" | "constant" | "variable";
};
```

One result of `ce.searchDefinitions()`.

</MemberCard>

<MemberCard>

### IntegrationProvider {#integrationprovider}

```ts
type IntegrationProvider = (integrand, variable, trace?) => Expression | null;
```

A symbolic-integration provider: given an integrand and the integration
variable, returns a closed-form antiderivative (an expression in `variable`),
or `null` when it cannot integrate it. See `IComputeEngine._integrationProvider`.

When an optional `trace` accumulator is passed (by `expr.explain('Integrate')`),
the provider appends a curated, whole-state step chain describing how the
antiderivative was found. The argument is backward-compatible: the plain
`Integrate` evaluator calls the provider with two arguments and never traces.

</MemberCard>

<MemberCard>

### ProtocolMember {#protocolmember}

```ts
type ProtocolMember = (
  | {
  kind: "function";
  signature: string;
 }
  | {
  kind: "readonly" | "readwrite";
  type: string;
 }) & {
  description: string;
};
```

One requirement of a protocol. A `function` member's signature is stored
VERBATIM, with `Self` unsubstituted: `Self` is a textual substitution token
(ruling P12), never a type the registry can resolve.

#### ProtocolMember.description?

```ts
description?: string;
```

The documentation of the member: the `///` comment before it in an
Epsil `protocol` statement, or `options.memberDescriptions` of
`ce.declareProtocol()`. Markdown.

</MemberCard>

<MemberCard>

### InferenceWriteEvent {#inferencewriteevent}

```ts
type InferenceWriteEvent = {
  name: string;
  binding: BoxedDefinition;
  target:   | BoxedValueDefinition
     | BoxedOperatorDefinition;
  from: BoxedType;
  to: BoxedType;
  kind: "inferred";
};
```

One write of inference evidence onto a definition, as delivered to
`IComputeEngine._noteInferenceWrite` — the single emission point whose
subscribers are the provenance history and the
narrowing sink. See `docs/TYPE-SYSTEM.md`
(phase 1).

</MemberCard>

<MemberCard>

### InferenceCauseContext {#inferencecausecontext}

```ts
type InferenceCauseContext = {
  operator: string;
  ops: ReadonlyArray<ExpressionInput>;
  expr: Expression;
};
```

The ambient canonicalization context recorded as the `cause` of provenance
entries: the operator expression being canonicalized when an inference
write fires. Kept as the operator name + the operand array as the
canonicalizer received it (possibly raw MathJSON — canonicalization has
not run yet); `expr` is the non-canonical materialization, built lazily on
the first write that records it (writes are rare — building an expression
per canonicalization would not be).

</MemberCard>

<MemberCard>

### ParameterRequirement {#parameterrequirement}

```ts
type ParameterRequirement = {
  type: BoxedType;
  cause: InferenceCauseContext;
  numeric: boolean;
};
```

What the uses of a parameter of a function literal required while the
literal is boxed (decision D18 of
`docs/plans/2026-11-11-bound-once-spec.md`): the type that a read of the
parameter gives, and the cause of the use that last changed it, recorded
as the provenance of the type when it is written on the definition.

</MemberCard>

<MemberCard>

### ParameterRecord {#parameterrecord}

```ts
type ParameterRecord = {
  requirements: Map<BoxedValueDefinition, ParameterRequirement>;
  env: UnitEnvironment;
  collectorDepth: number;
  memoStarts: number;
  created: Set<BoxedValueDefinition>;
};
```

The record of a function literal while it is boxed: the requirement of
each parameter, keyed by its value definition, and the environment of the
literal, which holds the entries that the uses of its parameters write
(outside a trial) and that a later use reads. The environment is made with
the record: a read of it is recorded only by the caches whose computation
started after that (`collectorDepth`, `objectDepCollectorDepth()`), as a
computation that started before boxes the literal again.

</MemberCard>

<MemberCard>

### JSImplementation {#jsimplementation}

```ts
type JSImplementation = {
  host: ProtocolHostHandler;
};
```

A HOST (JavaScript) implementation of a protocol member. A callback carries
no type information the engine can read, so — like a host-declared operator
handler — it is TRUSTED: only member-name coverage is checked, never its
signature. Boxed in a wrapper so it stays distinguishable from an Epsil
function literal (design P10).

</MemberCard>

<MemberCard>

### ProtocolHostHandler {#protocolhosthandler}

```ts
type ProtocolHostHandler = (...args) => unknown;
```

A host callback implementing one protocol member. Its arguments arrive as
boxed engine values (the receiver first, per P1); its result is boxed by the
engine. The engine cannot type-check it — that is what "trusted" means
here.

</MemberCard>

<MemberCard>

### ConformanceRecord {#conformancerecord}

```ts
type ConformanceRecord = {
  target: Type;
  targetKey: string;
  where: TypeParameter[];
  impl: Record<string, Expression | JSImplementation>;
  _authored: Record<string, Expression | JSImplementation>;
  _implOrigin: {
     batch: number;
     block: Expression;
    };
  pending: boolean;
  _pendingReason: string;
  _via: string;
  _derived: true;
  declaredByStatement: boolean;
};
```

One conformance edge: "this target type conforms to this protocol".
Conformances are add-only (monotone); only their implementations replace.

</MemberCard>

<MemberCard>

### SumConformanceRecord {#sumconformancerecord}

```ts
type SumConformanceRecord = {
  sum: string;
  impl: Record<string, Expression | JSImplementation>;
  block: Expression;
};
```

A whole-SUM conformance, as the author wrote it: `type shape is Area { … }`
where `shape` is a sum type (user ruling of 2026-09-22).

The statement itself registers one ordinary edge per variant — a sum names a
transparent alias of its variants, and an alias cannot conform — so this
record is bookkeeping, not an edge: it is what lets a variant the sum gains
in a LATER batch receive the same implementation block. The block is kept as
the author wrote it, BEFORE `Self` is bound: each variant's edge substitutes
`Self` with its own target, so the substituted block of one variant is the
wrong body for another.

</MemberCard>

<MemberCard>

### ProtocolRecord {#protocolrecord}

```ts
type ProtocolRecord = {
  name: string;
  members: Record<string, ProtocolMember>;
  description: string;
  extends: string[];
  conformances: ConformanceRecord[];
  declaredByStatement: boolean;
  _sumConformances: SumConformanceRecord[];
  _declOrigin: DeclarationOrigin;
};
```

A protocol declaration and every conformance registered against it.

</MemberCard>

<MemberCard>

### ProtocolMembersInput {#protocolmembersinput}

```ts
type ProtocolMembersInput = {
  functions: Record<string, string>;
  readonly: Record<string, string>;
  readwrite: Record<string, string>;
};
```

The host-API shape of a protocol's requirements. A flat
`Record<string, string>` cannot represent properties, hence the three
buckets (Appendix A "Host API").

</MemberCard>

<MemberCard>

### ProtocolImplementationInput {#protocolimplementationinput}

```ts
type ProtocolImplementationInput = {
  functions: Record<string, ProtocolHostHandler>;
  getters: Record<string, ProtocolHostHandler>;
  setters: Record<string, ProtocolHostHandler>;
};
```

The host-API shape of an IMPLEMENTATION block. Property handlers are given
under their surface names (`getters.hash`), not under the internal
`__get__hash` mangling (Appendix A "Properties": the mangling is an
implementation detail, not part of the public surface).

</MemberCard>

### IComputeEngine {#icomputeengine}

#### Extended by

- [`ComputeEngine`](#computeengine)

<MemberCard>

##### IComputeEngine.latexSyntax {#latexsyntax}

```ts
readonly latexSyntax: ILatexSyntax | undefined;
```

The LatexSyntax instance used for LaTeX parsing/serialization.
 `undefined` when no LatexSyntax was provided to the constructor and
 the entry point has no LaTeX support (the core-only bundle).

 To add a notation to a running engine, call
 `ce.latexSyntax.addEntries([...])`: later parses and serializations use
 the new entries. An engine created without the `latexSyntax` option
 has its own instance, so the change applies to that engine only. An
 instance given to several engines with the `latexSyntax` option is
 shared: the change applies to all of them.

</MemberCard>

<MemberCard>

##### IComputeEngine.latexOptions {#latexoptions}

```ts
latexOptions: Partial<ParseLatexOptions & SerializeLatexOptions>;
```

Engine-wide LaTeX parse/serialize options (e.g. `decimalSeparator`).
 Merged into every `parse()` and `toLatex()` call between LatexSyntax
 defaults and per-call overrides.

</MemberCard>

<MemberCard>

##### IComputeEngine.True {#true}

```ts
readonly True: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.False {#false}

```ts
readonly False: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.Pi {#pi}

```ts
readonly Pi: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.E {#e}

```ts
readonly E: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.Nothing {#nothing}

```ts
readonly Nothing: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.Missing {#missing}

```ts
readonly Missing: Expression;
```

The `Missing` symbol: an absent value whose position is preserved.

</MemberCard>

<MemberCard>

##### IComputeEngine.Zero {#zero}

```ts
readonly Zero: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.One {#one}

```ts
readonly One: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.Half {#half}

```ts
readonly Half: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.NegativeOne {#negativeone}

```ts
readonly NegativeOne: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.Two {#two}

```ts
readonly Two: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.I {#i}

```ts
readonly I: Expression;
```

ImaginaryUnit

</MemberCard>

<MemberCard>

##### IComputeEngine.NaN {#nan-1}

```ts
readonly NaN: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.PositiveInfinity {#positiveinfinity-1}

```ts
readonly PositiveInfinity: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.NegativeInfinity {#negativeinfinity-1}

```ts
readonly NegativeInfinity: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.ComplexInfinity {#complexinfinity}

```ts
readonly ComplexInfinity: Expression;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.context {#context}

```ts
readonly context: EvalContext;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.contextStack {#contextstack}

```ts
contextStack: readonly EvalContext[];
```

</MemberCard>

<MemberCard>

##### IComputeEngine.\_delegatedEvaluations {#_delegatedevaluations}

```ts
_delegatedEvaluations: number;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.macroNames {#macronames}

```ts
readonly macroNames: ReadonlySet<string>;
```

The names that were declared as a macro on this engine
(`ce.declare(name, { macro })`), in any scope. The set never shrinks: a
name stays in it after the scope of its declaration is popped, and after
a later declaration of the name that is not a macro. So a name that is
not in the set is not a macro in any scope, and a name that is in the set
may be one: `ce.lookupDefinition(name)` gives the definition that the
current scope reads. The set of an engine with no macro is empty.

</MemberCard>

<MemberCard>

##### IComputeEngine.timeRemaining {#timeremaining}

```ts
readonly timeRemaining: number;
```

The number of milliseconds left before the earliest deadline of the
active `withTimeLimit` spans (an enclosing span preempts a later inner
limit), and `0` or less once that deadline has passed. `Infinity` when
no active span has a time limit, which includes a `withStepBudget` span
with no `withTimeLimit` around it.

This value and [stepBudgetSpent](#stepbudgetspent-1) describe the span that is active
in the current synchronous code. Code that runs after an `await`, even
inside `withTimeLimit` or an `evaluateAsync()` call, is outside the
span: it reads `Infinity` and `false`.

The engine checks its deadline only inside its own work (evaluation,
canonicalization). A host loop that runs inside a span and does work of
its own (walking expressions, building a list) reads this value to stop
on time: `if (ce.timeRemaining <= 0) break;`.

A spent step budget does not change this value; read
[stepBudgetSpent](#stepbudgetspent-1) for it.

</MemberCard>

<MemberCard>

##### IComputeEngine.stepBudgetSpent {#stepbudgetspent}

```ts
readonly stepBudgetSpent: boolean;
```

True inside a `withStepBudget` span (or a span nested in one) when a
step budget of the current span or of an enclosing one is spent; false
otherwise, and always false outside any span.

When a budget is spent, the engine throws a `CancellationError`, but
code between the throw and the end of the span can catch it and return
a value. Such a value is partial. A host that stores values in a cache
reads this before a write, so that it does not keep a partial value.

</MemberCard>

<MemberCard>

##### IComputeEngine.stepsLeft {#stepsleft}

```ts
readonly stepsLeft: number | undefined;
```

The number of steps left in the budget of the innermost
`withStepBudget` span, or `undefined` when no such span is active.
It is negative once that budget is spent: after the throw that spends
it, each later check still counts one step, so `steps - ce.stepsLeft`
is the number of steps used only while the budget is not spent. A
`withTimeLimit` span nested in a step-budget span does not change it,
nor does a budget the engine opens for its own search: host code that
the engine calls during that search reads the host's budget.

Read inside the callback of `withStepBudget`, it tells the two things
[stepBudgetSpent](#stepbudgetspent-1) cannot: how many steps the span has used
(`steps - ce.stepsLeft`), and whether THIS span's budget is spent
(`ce.stepsLeft < 0`) rather than the budget of an enclosing span. A
step is an opaque unit: compare counts only on one engine version.
Like [timeRemaining](#timeremaining-1), it describes the span of the current
synchronous code.

</MemberCard>

<MemberCard>

##### IComputeEngine.iterationLimit {#iterationlimit}

```ts
iterationLimit: number;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.recursionLimit {#recursionlimit}

```ts
recursionLimit: number;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.maxCollectionSize {#maxcollectionsize}

```ts
maxCollectionSize: number;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.bignum {#bignum-1}

```ts
bignum: (a) => BigDecimal;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.complex {#complex-1}

```ts
complex: (a, b?) => Complex;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.angularUnit {#angularunit-1}

```ts
angularUnit: AngularUnit;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.roundingTies {#roundingties-1}

```ts
roundingTies: RoundingTies;
```

The rule that `Round` uses for a value halfway between two integers.
 See [RoundingTies](#roundingties). Default: `'away-from-zero'`.

</MemberCard>

<MemberCard>

##### IComputeEngine.costFunction {#costfunction-1}

```ts
costFunction: (expr) => number;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.simplificationRules {#simplificationrules}

```ts
simplificationRules: Rule[];
```

The rules used by `.simplify()` when no explicit `rules` option is passed.
 Initialized to the built-in simplification rules.
 Users can `push()` additional rules or replace the entire array.

</MemberCard>

<MemberCard>

##### IComputeEngine.solveRules {#solverules}

```ts
solveRules: Rule[];
```

The rules used by `solve()` to find roots of univariate expressions.
 Each rule matches a normalized equation `f(_x) = 0` — the unknown is
 the wildcard `_x` — and `replace` produces a root expression.
 Conditions should reject matches where other wildcards capture `_x`.
 Candidate roots are validated against the original equation, so an
 over-eager template degrades to a no-op rather than a wrong answer.
 Initialized to the built-in root-finding rules; `push()` to extend,
 assign to replace.

</MemberCard>

<MemberCard>

##### IComputeEngine.harmonizationRules {#harmonizationrules}

```ts
harmonizationRules: Rule[];
```

The rules used by `solve()` to transform an equation into equivalent,
 easier-to-solve forms before root-finding (e.g. `ln f(x) → f(x) - 1`).
 Same conventions and extension pattern as `solveRules`.

</MemberCard>

<MemberCard>

##### IComputeEngine.strict {#strict-1}

```ts
strict: boolean;
```

</MemberCard>

<MemberCard>

##### IComputeEngine.jit {#jit}

```ts
jit: "auto" | "off";
```

Whether the engine may implicitly generate and execute compiled code as
a performance optimization (auto-compiled `Map` drains, compiled numeric
quadrature/limit kernels). `'auto'` (default) attempts implicit
compilation and latches to `'off'` engine-wide on the first CSP
`EvalError`; `'off'` never attempts it. Explicit `compile()` is exempt.

</MemberCard>

<MemberCard>

##### IComputeEngine.workers {#workers}

```ts
workers: KernelPool | undefined;
```

The worker pool that `broadcastAsync()` of a compiled result uses, built
by the host with `createKernelPool()`. The engine creates no worker on
its own: with no pool every batch runs on the calling thread. One pool
can serve several engines, and it is read at each call.

</MemberCard>

<MemberCard>

##### IComputeEngine.arrayAllocation {#arrayallocation}

```ts
arrayAllocation: ((count, bytesPerCell) => boolean) | undefined;
```

The permission to allocate the storage of a mutable array, asked once
by `ArrayFrom` when the count of cells is known and before the engine
allocates the storage. `bytesPerCell` is the size of one cell: 1, 2, 4
or 8 for a machine cell, 4 for a tuple cell, 8 for an expression cell.
A result of `false`, an exception thrown by the function, and a failure
of the JavaScript allocation give the error `array-allocation-refused`.
It is a permission: the engine reports no release. It is not called for
the storage of an array that the host gives. With no function, the
engine refuses a storage of more than 2 GiB (2^31 bytes) for one array.

</MemberCard>

<MemberCard>

##### IComputeEngine.arrayCreated {#arraycreated}

```ts
arrayCreated: ((array) => void) | undefined;
```

A function called with each array that `ArrayFrom` made, after the
construction succeeded: not for a construction that failed, and not for
an array that the host made with [array](#array). The prelude code that
makes a raster gives the host no other reference to it, so a host that
limits the bytes alive holds a weak reference to each array here:

```ts
const alive = new Set<WeakRef<object>>();
ce.arrayCreated = (array) => alive.add(new WeakRef(array));
```

The engine does not catch an exception that the function throws: it
propagates out of the evaluation. A `TypeError`, a `RangeError` and a
`ReferenceError` are the exception: as from the handler of any
operator, they become the error `internal-error` of `ArrayFrom`.

</MemberCard>

<MemberCard>

##### IComputeEngine.trace {#trace}

```ts
trace: readonly string[];
```

A list of the function calls to the current evaluation context

</MemberCard>

<MemberCard>

##### IComputeEngine.effects {#effects-2}

```ts
get effects(): EffectHandlers
set effects(handlers: EffectHandlerOverrides): void
```

The host capabilities of this engine: the handlers the library operators
use to reach the host. `Print` and `Input` use `effects.console`.

The registry is an immutable object. Reading returns the registry that a
new evaluation would use. Assigning installs a new registry: the assigned
object is a COMPLETE description — a handler it does not mention returns
to its default, so `ce.effects = {}` restores every default. A `null`
handler denies the capability: an operator that needs it evaluates to an
`Error("capability-denied", …)` value.

```ts
const lines: string[] = [];
ce.effects = {
  console: { log: (line) => lines.push(line), readLine: () => undefined },
};
```

Each evaluation (`evaluate()`, `N()`, `evaluateAsync()`) uses the registry
that was installed when it started. An assignment does not change the
handlers of an evaluation that is already running.

For a change that must last for one block of code only, use
[`withEffects`](#witheffects).

</MemberCard>

<MemberCard>

##### IComputeEngine.precision {#precision-1}

```ts
get precision(): number
set precision(p: number | "auto" | "machine"): void
```

</MemberCard>

<MemberCard>

##### IComputeEngine.tolerance {#tolerance-2}

```ts
get tolerance(): number
set tolerance(v: number | "auto"): void
```

The absolute tolerance of `chop()`, of `.is()`, of `ApproxEqual` and of
the numeric algorithms (the residual test of `Solve`). The comparison
operators and the methods `.isEqual()`, `.isLess()` and the others do
not use it: they compare two numbers exactly, at the working precision.
A number is kept as set; `'auto'` is `10^(-precision + 2)`, recomputed
at each precision change.

</MemberCard>

<MemberCard>

##### IComputeEngine.declareProtocol() {#declareprotocol}

```ts
declareProtocol(name, members, options?): void
```

Declare a protocol (Appendix A "Host API"). Throws on error, including
on re-declaration — the Epsil statement route replaces instead (P5).

`options.extends` lists the PARENTS of the protocol, protocols that must
already be declared:

```js
ce.declareProtocol('PartialOrder', {
  functions: { compare: '(self: Self, other: Self) -> integer' },
});
ce.declareProtocol('LinearOrder', {}, { extends: ['PartialOrder'] });
```

A type that conforms to `LinearOrder` then conforms to `PartialOrder`
too: a conformance to a protocol registers a conformance to each of its
ancestors that the type does not already conform to, and the
implementation given to `declareProtocolImplementation` may implement
the members of every ancestor. A protocol may not declare a member that
one of its ancestors declares (`protocol-member-inherited`), and two
parents whose ancestors declare the same member name cannot be extended
together (`protocol-extends-member-conflict`). An `extends` value that is
not an array of strings, or that lists a name twice, throws
`invalid-protocol-declaration`; a name that is not a declared protocol
throws `protocol-unknown`.

`options.description` documents the protocol, and
`options.memberDescriptions` its members, by name (markdown): an editor
shows them in the hover of the protocol and in the help of a member.

####### name

`string`

####### members

[`ProtocolMembersInput`](#protocolmembersinput)

####### options?

####### extends?

readonly `string`[]

####### description?

`string`

####### memberDescriptions?

`Readonly`\<`Record`\<`string`, `string`\>\>

</MemberCard>

<MemberCard>

##### IComputeEngine.declareProtocolImplementation() {#declareprotocolimplementation}

```ts
declareProtocolImplementation(
   type, 
   protocol, 
   impl, 
   options?): void
```

Implement `protocol` for `type`, declaring the conformance edge if it is
not already registered (Appendix A "Host API").

THROWS on every error — the host channel; the Epsil statement route
returns error VALUES instead. A second host implementation of the same
(type, protocol) pair throws rather than replacing (P5).

The callbacks are JavaScript functions, so they carry no signature the
engine can check: they are trusted like host-declared operator handlers,
and only member-name coverage, unknown members and a `set` handler on a
`readonly` property are validated.

`options.where` declares a CONDITIONAL conformance: `type` is then a HEAD
PATTERN naming the variables (`'list<T>'`) and `where` is the clause SOURCE
that binds them (`'where T is Comparable'`; the `where` word may be
omitted). A malformed clause, or a head variable the clause does not bind,
throws.

####### type

`string`

####### protocol

`string`

####### impl

[`ProtocolImplementationInput`](#protocolimplementationinput)

####### options?

####### where?

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.conformsTo() {#conformsto}

```ts
conformsTo(type, protocol): boolean
```

Whether `type` conforms to `protocol`, answered without calling any of
the protocol's members. An unknown protocol answers `false`.

Inheritance included: a conformance registered for a supertype answers
for its subtypes. A CONDITIONAL conformance (`list<T> is P where T is
P`) recurses, deciding itself against `type`'s own arguments.

`type` may be a `TypeString`, parsed the way [IComputeEngine.type](#type-10)
parses one.

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)

####### protocol

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.withTimeLimit() {#withtimelimit}

```ts
withTimeLimit<T>(limit, fn): T
```

Run `fn` with at most `ms` milliseconds (numeric form) or `limit.ms`
(object form, which also accepts an attribution `label`). A tighter
enclosing span preempts this limit; use the label and
`CancellationError.attribution`/`spans` to tell which limit fired.

**⚠️ `fn` MUST be synchronous.** The span is restored in a synchronous
`finally`, so a `Promise`-returning (`async`) callback hands control back
at its first `await` while the span is still open: work that resumes after
that point runs **outside** the deadline and is never cancelled (see
`docs/TIMEOUT-MODEL.md` §6.4). An `expr.evaluateAsync()` call that `fn`
makes before its first `await` is the exception: the evaluation keeps
the span's deadline until it ends
(`ce.withTimeLimit(20, () => { p = expr.evaluateAsync(); })`). For
cancellation that is not a time limit, use
`expr.evaluateAsync({ signal })` with an `AbortSignal`.

• T

####### limit

  \| `number`
  \| \{
  `ms`: `number`;
  `label`: `string`;
 \}

####### fn

() => `T` *extends* `Promise`\<`unknown`\> ? `never` : `T`

</MemberCard>

<MemberCard>

##### IComputeEngine.withStepBudget() {#withstepbudget}

```ts
withStepBudget<T>(limit, fn): T
```

Run `fn` with at most `limit.steps` steps of engine work: a hang guard
that fires at the same point on every machine, unlike a wall-clock
limit. A step is one of the engine's cooperative cancellation checks —
an opaque unit, deterministic for one computation on one engine state,
but not a measure of cost and not comparable across engine versions;
tune the budget empirically and keep a `withTimeLimit` span outside it.
A spent budget throws a `CancellationError` with `cause: 'step-budget'`
and the span's `label` as its `attribution`.

**⚠️ `fn` MUST be synchronous**, as for `withTimeLimit`.

• T

####### limit

####### steps

`number`

####### label?

`string`

####### fn

() => `T` *extends* `Promise`\<`unknown`\> ? `never` : `T`

</MemberCard>

<MemberCard>

##### IComputeEngine.withEffects() {#witheffects}

```ts
withEffects<T>(overrides, fn): T
```

Run `fn` with some host capabilities replaced or denied, then put the
previous ones back. Evaluations that START inside `fn` use the changed
registry.

`overrides` is applied on top of the registry in effect when
`withEffects` is called, so calls nest: a capability an inner call does
not mention keeps the handler of the outer call. A `null` value denies the
capability, even if it has a default handler — this is how to evaluate an
expression that is not trusted:

```ts
const result = ce.withEffects({ console: null }, () => expr.evaluate());
```

The previous registry is put back when `fn` returns or throws. If `fn`
returns a promise, it is put back when that promise settles (fulfilled or
rejected), and `withEffects` returns a promise that settles the same way.

An asynchronous evaluation keeps the registry it started with, so an
evaluation that started BEFORE `withEffects` was called is not changed by
it. But while the promise of an asynchronous `fn` is pending, the changed
registry is the installed one: an unrelated evaluation that starts during
that time, from other code, also uses it. Start such evaluations before
calling `withEffects`, or use a separate engine.

• T

####### overrides

[`EffectHandlerOverrides`](#effecthandleroverrides)

####### fn

() => `T`

</MemberCard>

<MemberCard>

##### IComputeEngine.withEvaluationContext() {#withevaluationcontext}

```ts
withEvaluationContext<T>(options, fn): T
```

Run the synchronous `fn` in the evaluation context that `options`
carries, then put the previous context back, and return the result of
`fn`.

For an `evaluateAsync` handler. The handler receives `options`, which
carry the evaluation context of the evaluation that called it: the host
capability registry, and the lexical scopes of the scoped operators that
the evaluation is inside (the scope of the index of a `Sum`, for
example). While the handler is suspended at an `await`, other code can
run on the same engine, so the engine does not keep that context
installed for the handler. Before the first `await`, the context is in
place. After it, synchronous work that reads the scope — canonicalizing
a held operand (`x.canonical`), `ce.box()`, `ce.parse()`, `evaluate()`,
`ce.assign()` — sees the global scope unless it runs inside `fn`. An
index of an enclosing `Sum` then stays symbolic, and a new global
symbol with its name is declared.

```ts
ce.declare('Late', {
  signature: '(integer) -> integer',
  lazy: true,
  evaluateAsync: async ([x], options) => {
    await delay(1);
    return ce
      .withEvaluationContext(options, () => x.canonical)
      .evaluateAsync(options);
  },
});
```

A nested `evaluateAsync(options)` call does not need it: the options
carry the context to that evaluation.

If `fn` returns a promise, only the synchronous part of `fn`, up to its
first `await`, runs in the context.

• T

####### options

`Partial`\<`EvaluateOptions`\> \| `undefined`

####### fn

() => `T`

</MemberCard>

<MemberCard>

##### IComputeEngine.chop() {#chop}

###### chop(n)

```ts
chop(n): number
```

####### n

`number`

###### chop(n)

```ts
chop(n): 0 | BigDecimal
```

####### n

`BigDecimal`

###### chop(n)

```ts
chop(n): number | BigDecimal
```

####### n

`number` \| `BigDecimal`

</MemberCard>

<MemberCard>

##### IComputeEngine.array() {#array}

```ts
array(storage, cellType?): Expression & ArrayInterface
```

**`Experimental`**

A new mutable array that adopts the typed array `storage` as its cells,
with no pass over the cells and no copy: `ce.array(s).cells === s`.

Without `cellType`, the cell type is the full range of the storage kind:
`integer<0..255>` for a `Uint8Array`, `integer<-128..127>` for an
`Int8Array`, `integer<0..65535>` for a `Uint16Array`,
`integer<-32768..32767>` for an `Int16Array`, `integer<0..4294967295>`
for a `Uint32Array`, `integer<-2147483648..2147483647>` for an
`Int32Array` and `real` for a `Float64Array`.

A `cellType` must select the storage kind of `storage`. A tuple of four
bytes (`type Pixel = tuple<r: Byte, g: Byte, b: Byte, a: Byte>`) takes a
`Uint8Array` with four bytes for each cell, and the count is
`storage.length / 4`. The bytes of an `ImageData` are shared with:

```ts
const image = ce.array(new Uint8Array(data.data.buffer), 'Pixel');
```

The cells are not checked: each must hold a value of the cell type (see
`ArrayInterface`). `ce.arrayAllocation` and `ce.arrayCreated` are not
called.

Throws a `TypeError` for a value that is not a typed array, for a typed
array of a kind that has no cell type (`Float32Array`, `BigInt64Array`,
`BigUint64Array`, `Uint8ClampedArray`), for a view of a
`SharedArrayBuffer` or of a resizable `ArrayBuffer`, for a `cellType`
with expression cells or of
another storage kind, and for a tuple cell type with a length that is
not a multiple of 4.

####### storage

  \| `Uint8Array`\<`ArrayBufferLike`\>
  \| `Int8Array`\<`ArrayBufferLike`\>
  \| `Uint16Array`\<`ArrayBufferLike`\>
  \| `Int16Array`\<`ArrayBufferLike`\>
  \| `Uint32Array`\<`ArrayBufferLike`\>
  \| `Int32Array`\<`ArrayBufferLike`\>
  \| `Float64Array`\<`ArrayBufferLike`\>

####### cellType?

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

</MemberCard>

<MemberCard>

##### IComputeEngine.expr() {#expr-2}

```ts
expr(expr, options?): Expression
```

####### expr

  \| [`NumericValue`](#abstract-numericvalue)
  \| [`ExpressionInput`](#expressioninput)

####### options?

####### form?

[`FormOption`](#formoption)

####### scope?

`Scope`

</MemberCard>

<MemberCard>

##### IComputeEngine.~~box()~~ {#box}

```ts
box(expr, options?): Expression
```

####### expr

  \| [`NumericValue`](#abstract-numericvalue)
  \| [`ExpressionInput`](#expressioninput)

####### options?

####### form?

[`FormOption`](#formoption)

####### scope?

`Scope`

###### Deprecated

Use `expr()` instead.

</MemberCard>

<MemberCard>

##### IComputeEngine.rebind() {#rebind}

```ts
rebind(expr, options?): Expression
```

Rebuild `expr` as if `ce.expr(expr.json, { form, scope })` had been
called — every symbol resolves afresh in `scope` (or the current scope)
— without serializing `expr` to MathJSON.

`ce.expr(expr, { scope })` on an already-boxed expression keeps the
bindings the expression was boxed with; it never re-resolves a symbol.
This is the operation that does. Use it when an expression built under
one set of declarations must be read under another: a body boxed in a
shadow scope, a row re-classified after a declaration changed.

For the canonical and partial forms the MathJSON is built as a DAG — one
array per DISTINCT function node, shared by every parent that reads it
(a leaf contributes its own constant-size MathJSON) — where
`expr.json` writes a tree, one copy of a shared node per path. That
MathJSON is then boxed by the ordinary route, so the result matches
`ce.expr(expr.json, …)` by construction, including for an expression
that already holds an `Error` node. Canonical boxing still visits every
path, as it does for any MathJSON. The raw and structural forms
canonicalize nothing, so each distinct node is rebuilt once and a shared
sub-expression stays shared in the result as well.

- `form`: `'canonical'` (default), `'structural'`, `'raw'`, or a
  partial form such as `['Flatten', 'Order']`.
- `scope`: the lexical scope the rebuild resolves and declares in.

Verbatim LaTeX and source positions are dropped, as the MathJSON route
drops them. A mutable object is rebuilt as its record snapshot, as that
route boxes it.

To give a name a value for one evaluation, or to hide its value, use
`withValues()`, not a declaration in a pushed scope followed by
`rebind()`: a stored function that the expression calls reads the names
of the scope it was defined in, which a pushed scope does not change.

####### expr

[`Expression`](#expression-5)

####### options?

####### form?

[`FormOption`](#formoption)

####### scope?

`Scope`

</MemberCard>

<MemberCard>

##### IComputeEngine.parse() {#parse-1}

###### parse(latex, options)

```ts
parse(latex, options?): Expression
```

Parse a LaTeX string and return a boxed expression.

This is a convenience method equivalent to `ce.expr(parse(latex))`,
but uses the engine's symbol definitions for better parsing accuracy.

`options.scope` RECEIVES the parse's writes: the whole parse runs with
that scope as the current lexical scope, so name resolution (including
the parser's symbol oracle) walks `scope → parents`, and every
declaration and inference made while it runs lands rooted there. Boxing
itself declares no name. Discarding the scope discards the writes. Use `ce.createScope()` to make one that can be read
back.

`options.speculative` leaves NO trace in the engine's type state: the
parse runs inside a transient scope (declarations and inferences land
there and are discarded with it), and every ambient symbol whose type is currently
inferred is shadowed in that scope with its current type — so a
narrowing use in `latex` refines the discarded shadow instead of
persistently narrowing the ambient symbol. Use it for derive-style
parses that only READ the result (its type, structure, or
serialization): the result's bindings refer to the discarded scope, so
do not retain, evaluate, or compare it against later expressions.
Mutually exclusive with `scope`.

####### latex

`string`

####### options?

`Partial`\<[`ParseLatexOptions`](#parselatexoptions)\> & \{
  `form`: [`FormOption`](#formoption);
  `scope`: `Scope`;
  `speculative`: `boolean`;
 \}

###### parse(latex, options)

```ts
parse(latex, options?): Expression | null
```

####### latex

`string` \| `null`

####### options?

`Partial`\<[`ParseLatexOptions`](#parselatexoptions)\> & \{
  `form`: [`FormOption`](#formoption);
  `scope`: `Scope`;
  `speculative`: `boolean`;
 \}

</MemberCard>

<MemberCard>

##### IComputeEngine.appliedNonFunctions() {#appliednonfunctions}

```ts
appliedNonFunctions(latex): string[]
```

The symbols that appear in function-application syntax `f(…)` in `latex`
but are not defined as functions in the current scope (so they parse as
implicit multiplication or are left unresolved). Scope-aware and
side-effect-free. Intended to flag calls to undefined functions in tools
such as notebooks; intersect with [Expression.freeVariables](#freevariables)
to drop deliberate multiplication of defined values.

Only parenthesized-group application is detected: a symbol juxtaposed
with a matrix environment (`\mathrm{Eigenvalues}\begin{pmatrix}…`) is
not reported, since a matrix never reaches the symbol-with-delimiter
juxtaposition analysis.

####### latex

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.function() {#function}

```ts
function(name, ops, options?): Expression
```

####### name

`string`

####### ops

readonly [`ExpressionInput`](#expressioninput)[]

####### options?

####### metadata?

[`Metadata`](#metadata)

####### form?

[`FormOption`](#formoption)

####### scope?

`Scope`

</MemberCard>

<MemberCard>

##### IComputeEngine.number() {#number-1}

###### number(value, options)

```ts
number(value, options?): Expression
```

Create a complex number from its real part and its imaginary part, each
a JavaScript `number` or a `BigDecimal`.

When the engine works above machine precision (`ce.precision` greater
than 15), a `BigDecimal` part is kept at the precision it holds: a part
too small or too large for a double (`1e-800`, `1e800`) or with more
than 16 significant digits is not rounded to a double. This is the
lossless alternative to `ce.number(ce.complex(re, im))`: `ce.complex()`
returns a `Complex` object, whose parts are always doubles. At machine
precision, both parts are rounded to doubles: there
`{ re: ce.bignum('1e-800'), im: ce.bignum(2) }` gives `2i`.

When the imaginary part is zero (a `number` or a `BigDecimal`), the
result is a real number.

When both parts are integers, the result is the EXACT Gaussian integer,
as `ce.number(2)` is the exact `2`: a part is an integer when it is a
`number` that is a safe integer, or an integer-valued `BigDecimal` whose
exponent is at most `10^6` (also at machine precision, and also outside
the double range). When a part has a fraction, is a `number` past the
safe integers, or is a `BigDecimal` with a larger exponent (`1e2000000`),
the result is a float. A `Complex` given to `ce.number()` or `ce.box()`
does not follow this rule: it holds two doubles, so it is always a
float (`ce.number(new Complex(2, 3))` is the float `2.0 + 3.0i`).

```js
ce.precision = 30;
ce.number({ re: ce.bignum('1e-800'), im: ce.bignum(2) });
// ➔ a complex number with the real part 1e-800 and the imaginary part 2
ce.number({ re: 1, im: 0 });
// ➔ 1
ce.number({ re: 2, im: 3 }).isExact;
// ➔ true
ce.number({ re: 2.5, im: 3 }).isExact;
// ➔ false
```

####### value

####### re

`number` \| `BigDecimal`

####### im

`number` \| `BigDecimal`

####### options?

####### metadata?

[`Metadata`](#metadata)

####### canonical?

[`CanonicalOptions`](#canonicaloptions)

###### number(value, options)

```ts
number(value, options?): Expression
```

Create a number literal.

A JavaScript `number` that is a safe integer (`Number.isSafeInteger()`,
at most `2^53 − 1` in magnitude) is an exact integer. Any other
`number` is a float. Above machine precision a float holds its shortest
decimal, the digits `String(x)` prints, not the exact binary value of
the double: `ce.number(0.1)` is the decimal `0.1`, and
`ce.number(2 ** 60)` is `1152921504606847000`, not
`1152921504606846976`. At machine precision a float is the double.

An integer beyond `2^53 − 1` is exact when it is given as a `bigint` or
as a string of digits.

```js
ce.number(2 ** 60).isExact;
// ➔ false
ce.box(['Remainder', 2 ** 60, 7]).evaluate();
// ➔ -3 (the remainder of 1152921504606847000)
ce.function('Remainder', [ce.number(2n ** 60n), ce.number(7)]).evaluate();
// ➔ 1
ce.number('1152921504606846976').isExact;
// ➔ true
```

####### value

  \| `string`
  \| `number`
  \| `bigint`
  \| [`MathJsonNumberObject`](#mathjsonnumberobject)
  \| `BigDecimal`
  \| [`Rational`](#rational-1)
  \| [`NumericValue`](#abstract-numericvalue)
  \| `Complex`

####### options?

####### metadata?

[`Metadata`](#metadata)

####### canonical?

[`CanonicalOptions`](#canonicaloptions)

</MemberCard>

<MemberCard>

##### IComputeEngine.symbol() {#symbol}

```ts
symbol(sym, options?): Expression
```

####### sym

`string`

####### options?

####### canonical?

[`CanonicalOptions`](#canonicaloptions)

####### metadata?

[`Metadata`](#metadata)

####### autoDeclare?

`boolean`

</MemberCard>

<MemberCard>

##### IComputeEngine.string() {#string-1}

```ts
string(s, metadata?): Expression
```

####### s

`string`

####### metadata?

[`Metadata`](#metadata)

</MemberCard>

<MemberCard>

##### IComputeEngine.character() {#character-1}

```ts
character(s, metadata?): Expression
```

Create a boxed character — one user-perceived character.

`s` must be exactly one grapheme cluster after NFC normalization; use the
`CharacterFrom` operator when the content is not known to satisfy that, as
it reports a diagnostic instead.

####### s

`string`

####### metadata?

[`Metadata`](#metadata)

</MemberCard>

<MemberCard>

##### IComputeEngine.error() {#error-1}

```ts
error(message, where?): Expression
```

####### message

`string` \| `string`[]

####### where?

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.typeError() {#typeerror}

```ts
typeError(expectedType, actualType, where?): Expression
```

####### expectedType

[`Type`](#type-3)

####### actualType

  \| [`Type`](#type-3)
  \| [`BoxedType`](#boxedtype)
  \| `undefined`

####### where?

[`ExpressionInput`](#expressioninput)

</MemberCard>

<MemberCard>

##### IComputeEngine.hold() {#hold}

```ts
hold(expr): Expression
```

####### expr

[`ExpressionInput`](#expressioninput)

</MemberCard>

<MemberCard>

##### IComputeEngine.tuple() {#tuple}

###### tuple(elements)

```ts
tuple(...elements): Expression
```

####### elements

...readonly `number`[]

###### tuple(elements)

```ts
tuple(...elements): Expression
```

####### elements

...readonly [`Expression`](#expression-5)[]

</MemberCard>

<MemberCard>

##### IComputeEngine.list() {#list}

```ts
list(values): Expression
```

A `List` of numbers, built without boxing each element.

The elements are copied into a frozen array of machine numbers that the
list keeps as its store: `count`, `at`, `type`, `isSame` and `array`
answer from it, and the boxed operands are built only if `ops` is read.
The result is an ordinary canonical `List` in every other respect.

`values` may be a `number[]`, a `Float64Array` or any array-like of
numbers. Its `length` must be a non-negative safe integer and each
element a JS number; anything else throws a `TypeError`. `-0` is stored
as `+0`.

Use it to hand a large numeric list to the engine cheaply, and read it
back with `expr.array`.

####### values

`ArrayLike`\<`number`\>

</MemberCard>

<MemberCard>

##### IComputeEngine.type() {#type-10}

```ts
type(type): BoxedType
```

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

</MemberCard>

<MemberCard>

##### IComputeEngine.rules() {#rules-1}

```ts
rules(rules, options?): BoxedRuleSet
```

####### rules

`Rule` \| readonly Rule \| BoxedRule[] \| `BoxedRuleSet` \| `null` \| `undefined`

####### options?

####### canonical?

`boolean`

####### purpose?

[`RulePurpose`](#rulepurpose)

Default purpose applied to any rule in the set that doesn't carry
 its own `purpose` tag (a per-rule tag takes precedence).

</MemberCard>

<MemberCard>

##### IComputeEngine.getRuleSet() {#getruleset}

```ts
getRuleSet(id?): BoxedRuleSet | undefined
```

####### id?

`"harmonization"` \| `"solve-univariate"` \| `"standard-simplification"`

</MemberCard>

<MemberCard>

##### IComputeEngine.pushScope() {#pushscope}

```ts
pushScope(scope?, name?): void
```

####### scope?

`Scope`

####### name?

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.popScope() {#popscope}

```ts
popScope(): void
```

</MemberCard>

<MemberCard>

##### IComputeEngine.createScope() {#createscope}

```ts
createScope(bindings?, parent?): InspectableScope
```

####### bindings?

`Record`\<`string`, 
  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`TaggedValueDefinition`](#taggedvaluedefinition)
  \| [`TaggedOperatorDefinition`](#taggedoperatordefinition)\>

####### parent?

`Scope`

</MemberCard>

<MemberCard>

##### IComputeEngine.lookupDefinition() {#lookupdefinition-1}

```ts
lookupDefinition(id): BoxedDefinition | undefined
```

####### id

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.assign() {#assign}

###### assign(ids)

```ts
assign(ids): IComputeEngine
```

####### ids

\{\}

###### assign(id, value)

```ts
assign(id, value): IComputeEngine
```

####### id

`string`

####### value

`AssignValue`

###### assign(arg1, arg2)

```ts
assign(arg1, arg2?): IComputeEngine
```

####### arg1

`string` \| \{\}

####### arg2?

`AssignValue`

</MemberCard>

<MemberCard>

##### IComputeEngine.withValues() {#withvalues}

```ts
withValues<T>(values, fn): T
```

Run `fn` with each symbol of `values` bound to the given value, and
put back the earlier value and type of each symbol when `fn` returns or
throws. `fn` must be synchronous.

• T

####### values

\{\}

####### fn

() => `T`

</MemberCard>

<MemberCard>

##### IComputeEngine.declareType() {#declaretype}

```ts
declareType(name, type, options?): void
```

####### name

`string`

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

####### options?

####### alias?

`boolean`

####### fromStatement?

`boolean`

####### mint?

`boolean`

Whether the declaration also declares a value-level constructor
of the same name (`point(1, 2)` for `type point = tuple<…>`). Default
`true`. A VALUE KIND uses `false`: its type is a nominal type defined
as exactly `value` (`ce.declareType('gf8', 'value', { mint: false })`),
and its values are made by the head that declares its arithmetic
(`GF8(3)`), so a second constructor with no arithmetic must not
exist. See the `arithmetic` field of `OperatorDefinition`.

####### typeParams?

[`TypeParamsOption`](#typeparamsoption)

</MemberCard>

<MemberCard>

##### IComputeEngine.declare() {#declare}

###### declare(symbols)

```ts
declare(symbols): IComputeEngine
```

####### symbols

\{\}

###### declare(id, type, scope)

```ts
declare(id, type, scope?): IComputeEngine
```

####### id

`string`

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)

####### scope?

  \| `Scope`
  \| [`DeclareOptions`](#declareoptions) & \{
  `extend`: `false`;
 \}

###### declare(id, patch, options)

```ts
declare(id, patch, options): IComputeEngine
```

####### id

`string`

####### patch

[`OperatorDefinitionPatch`](#operatordefinitionpatch)

####### options

[`DeclareOptions`](#declareoptions) & \{
  `extend`: `true`;
 \}

###### declare(id, def, scope)

```ts
declare(id, def, scope?): IComputeEngine
```

####### id

`string`

####### def

[`SymbolDefinitionInput`](#symboldefinitioninput)

####### scope?

  \| `Scope`
  \| [`DeclareOptions`](#declareoptions) & \{
  `extend`: `false`;
 \}

###### declare(arg1, arg2, arg3)

```ts
declare(arg1, arg2?, arg3?): IComputeEngine
```

####### arg1

`string` \| \{\}

####### arg2?

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| `Partial`\<`OnlyFirst`\<[`ValueDefinition`](#valuedefinition), [`BaseDefinition`](#basedefinition) & \{
  `holdUntil`: `"never"` \| `"evaluate"` \| `"N"`;
  `type`:   \| `string`
     \| [`RecordType`](#recordtype)
     \| [`AlgebraicType`](#algebraictype)
     \| [`NegationType`](#negationtype)
     \| [`CollectionType`](#collectiontype)
     \| [`ListType`](#listtype)
     \| [`SetType`](#settype)
     \| [`BroadcastableType`](#broadcastabletype)
     \| [`ObjectType`](#objecttype)
     \| [`ArrayType`](#arraytype)
     \| [`DictionaryType`](#dictionarytype)
     \| [`TupleType`](#tupletype)
     \| [`SymbolType`](#symboltype)
     \| [`ExpressionType`](#expressiontype)
     \| [`NumericType`](#numerictype)
     \| [`FunctionSignature`](#functionsignature)
     \| [`ValueType`](#valuetype)
     \| [`TypeVariable`](#typevariable)
     \| [`TypeReference`](#typereference)
     \| [`BoxedType`](#boxedtype);
  `inferred`: `boolean`;
  `effectsDeclared`: `boolean`;
  `value`:   \| [`ExpressionInput`](#expressioninput)
     \| ((`ce`) => [`Expression`](#expression-5) \| `null`);
  `macro`: [`MathJsonExpression`](#mathjsonexpression);
  `eq`: (`a`) => `boolean` \| `undefined`;
  `neq`: (`a`) => `boolean` \| `undefined`;
  `cmp`: (`a`) => `"<"` \| `">"` \| `"="` \| `undefined`;
  `collection`: [`CollectionHandlers`](#collectionhandlers);
  `subscriptEvaluate`: (`subscript`, `options`) => [`Expression`](#expression-5) \| `undefined`;
 \} & `Partial`\<[`BaseDefinition`](#basedefinition)\> & `Partial`\<[`OperatorDefinitionFlags`](#operatordefinitionflags)\> & \{
  `type`: [`OperatorTypeHandlerOnTypes`](#operatortypehandlerontypes);
  `signature`:   \| `string`
     \| [`RecordType`](#recordtype)
     \| [`AlgebraicType`](#algebraictype)
     \| [`NegationType`](#negationtype)
     \| [`CollectionType`](#collectiontype)
     \| [`ListType`](#listtype)
     \| [`SetType`](#settype)
     \| [`BroadcastableType`](#broadcastabletype)
     \| [`ObjectType`](#objecttype)
     \| [`ArrayType`](#arraytype)
     \| [`DictionaryType`](#dictionarytype)
     \| [`TupleType`](#tupletype)
     \| [`SymbolType`](#symboltype)
     \| [`ExpressionType`](#expressiontype)
     \| [`NumericType`](#numerictype)
     \| [`FunctionSignature`](#functionsignature)
     \| [`ValueType`](#valuetype)
     \| [`TypeVariable`](#typevariable)
     \| [`TypeReference`](#typereference)
     \| [`BoxedType`](#boxedtype);
  `parameters`:   \| `Readonly`\<`Record`\<`string`, [`ParameterDocumentation`](#parameterdocumentation)\>\>
     \| readonly [`ParameterDocumentation`](#parameterdocumentation)[];
  `inferredSignature`: `boolean`;
  `sgn`: (`ops`, `options`) => [`Sign`](#sign) \| `undefined`;
  `isPositive`: `boolean`;
  `isNonNegative`: `boolean`;
  `isNegative`: `boolean`;
  `isNonPositive`: `boolean`;
  `even`: (`ops`, `options`) => `boolean` \| `undefined`;
  `complexity`: `number`;
  `canonical`: (`ops`, `options`) => [`Expression`](#expression-5) \| `null`;
  `evaluate`:   \| [`Expression`](#expression-5)
     \| ((`ops`, `options`) => [`Expression`](#expression-5) \| `undefined`);
  `evaluateAsync`: (`ops`, `options`) => `Promise`\<[`Expression`](#expression-5) \| `undefined`\>;
  `evaluateMod`: [`EvaluateModHandler`](#evaluatemodhandler);
  `evalDimension`: (`args`, `options`) => [`Expression`](#expression-5);
  `derivative`: [`OperatorDerivative`](#operatorderivative);
  `compile`: [`OperatorCompileHandler`](#operatorcompilehandler);
  `eq`: (`a`, `b`, `prover?`) => `boolean` \| `undefined`;
  `neq`: (`a`, `b`) => `boolean` \| `undefined`;
  `collection`: [`CollectionHandlers`](#collectionhandlers);
  `arithmetic`: [`ArithmeticDefinition`](#arithmeticdefinition);
  `canEnumerate`: (`expr`) => `boolean` \| `undefined`;
  `elementCount`: (`expr`) => `number` \| `undefined`;
  `elementAt`: (`expr`, `index`) => [`Expression`](#expression-5) \| `undefined`;
  `inferOperandTypes`: (`ops`, `requirement`) => 
     \| readonly (
     \| [`Type`](#type-3)
     \| \{
     `replace`: ...;
    \}
     \| `undefined`)[]
     \| `undefined`;
 \}\>\>
  \| `Partial`\<`OnlyFirst`\<[`OperatorDefinition`](#operatordefinition), [`BaseDefinition`](#basedefinition) & \{
  `holdUntil`: `"never"` \| `"evaluate"` \| `"N"`;
  `type`:   \| `string`
     \| [`RecordType`](#recordtype)
     \| [`AlgebraicType`](#algebraictype)
     \| [`NegationType`](#negationtype)
     \| [`CollectionType`](#collectiontype)
     \| [`ListType`](#listtype)
     \| [`SetType`](#settype)
     \| [`BroadcastableType`](#broadcastabletype)
     \| [`ObjectType`](#objecttype)
     \| [`ArrayType`](#arraytype)
     \| [`DictionaryType`](#dictionarytype)
     \| [`TupleType`](#tupletype)
     \| [`SymbolType`](#symboltype)
     \| [`ExpressionType`](#expressiontype)
     \| [`NumericType`](#numerictype)
     \| [`FunctionSignature`](#functionsignature)
     \| [`ValueType`](#valuetype)
     \| [`TypeVariable`](#typevariable)
     \| [`TypeReference`](#typereference)
     \| [`BoxedType`](#boxedtype);
  `inferred`: `boolean`;
  `effectsDeclared`: `boolean`;
  `value`:   \| [`ExpressionInput`](#expressioninput)
     \| ((`ce`) => [`Expression`](#expression-5) \| `null`);
  `macro`: [`MathJsonExpression`](#mathjsonexpression);
  `eq`: (`a`) => `boolean` \| `undefined`;
  `neq`: (`a`) => `boolean` \| `undefined`;
  `cmp`: (`a`) => `"<"` \| `">"` \| `"="` \| `undefined`;
  `collection`: [`CollectionHandlers`](#collectionhandlers);
  `subscriptEvaluate`: (`subscript`, `options`) => [`Expression`](#expression-5) \| `undefined`;
 \} & `Partial`\<[`BaseDefinition`](#basedefinition)\> & `Partial`\<[`OperatorDefinitionFlags`](#operatordefinitionflags)\> & \{
  `type`: [`OperatorTypeHandlerOnTypes`](#operatortypehandlerontypes);
  `signature`:   \| `string`
     \| [`RecordType`](#recordtype)
     \| [`AlgebraicType`](#algebraictype)
     \| [`NegationType`](#negationtype)
     \| [`CollectionType`](#collectiontype)
     \| [`ListType`](#listtype)
     \| [`SetType`](#settype)
     \| [`BroadcastableType`](#broadcastabletype)
     \| [`ObjectType`](#objecttype)
     \| [`ArrayType`](#arraytype)
     \| [`DictionaryType`](#dictionarytype)
     \| [`TupleType`](#tupletype)
     \| [`SymbolType`](#symboltype)
     \| [`ExpressionType`](#expressiontype)
     \| [`NumericType`](#numerictype)
     \| [`FunctionSignature`](#functionsignature)
     \| [`ValueType`](#valuetype)
     \| [`TypeVariable`](#typevariable)
     \| [`TypeReference`](#typereference)
     \| [`BoxedType`](#boxedtype);
  `parameters`:   \| `Readonly`\<`Record`\<`string`, [`ParameterDocumentation`](#parameterdocumentation)\>\>
     \| readonly [`ParameterDocumentation`](#parameterdocumentation)[];
  `inferredSignature`: `boolean`;
  `sgn`: (`ops`, `options`) => [`Sign`](#sign) \| `undefined`;
  `isPositive`: `boolean`;
  `isNonNegative`: `boolean`;
  `isNegative`: `boolean`;
  `isNonPositive`: `boolean`;
  `even`: (`ops`, `options`) => `boolean` \| `undefined`;
  `complexity`: `number`;
  `canonical`: (`ops`, `options`) => [`Expression`](#expression-5) \| `null`;
  `evaluate`:   \| [`Expression`](#expression-5)
     \| ((`ops`, `options`) => [`Expression`](#expression-5) \| `undefined`);
  `evaluateAsync`: (`ops`, `options`) => `Promise`\<[`Expression`](#expression-5) \| `undefined`\>;
  `evaluateMod`: [`EvaluateModHandler`](#evaluatemodhandler);
  `evalDimension`: (`args`, `options`) => [`Expression`](#expression-5);
  `derivative`: [`OperatorDerivative`](#operatorderivative);
  `compile`: [`OperatorCompileHandler`](#operatorcompilehandler);
  `eq`: (`a`, `b`, `prover?`) => `boolean` \| `undefined`;
  `neq`: (`a`, `b`) => `boolean` \| `undefined`;
  `collection`: [`CollectionHandlers`](#collectionhandlers);
  `arithmetic`: [`ArithmeticDefinition`](#arithmeticdefinition);
  `canEnumerate`: (`expr`) => `boolean` \| `undefined`;
  `elementCount`: (`expr`) => `number` \| `undefined`;
  `elementAt`: (`expr`, `index`) => [`Expression`](#expression-5) \| `undefined`;
  `inferOperandTypes`: (`ops`, `requirement`) => 
     \| readonly (
     \| [`Type`](#type-3)
     \| \{
     `replace`: ...;
    \}
     \| `undefined`)[]
     \| `undefined`;
 \}\>\>
  \| [`BoxedOperatorDefinition`](#boxedoperatordefinition)
  \| [`OperatorDefinitionPatch`](#operatordefinitionpatch)

####### arg3?

`Scope` \| [`DeclareOptions`](#declareoptions)

</MemberCard>

<MemberCard>

##### IComputeEngine.loadLibrary() {#loadlibrary}

```ts
loadLibrary(library): IComputeEngine
```

Load a library on an engine that is already constructed. Its
definitions are declared in the global scope, as with `ce.declare()`,
and its name is recorded (see `libraryOf()`). Each library in its
`requires` list must already be loaded.

####### library

[`LibraryDefinition`](#librarydefinition)

</MemberCard>

<MemberCard>

##### IComputeEngine.libraryOf() {#libraryof}

```ts
libraryOf(name): string | undefined
```

The name of the library whose definition `name` resolves to in the
current scope (`'trigonometry'` for `Sin`), or `undefined` for a name
that no library defines or that a declaration shadows.

####### name

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.assume() {#assume}

```ts
assume(predicate): AssumeResult
```

####### predicate

`string` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### IComputeEngine.infer() {#infer}

```ts
infer(exprs): InferResult
```

**`Experimental`**

Declare the names that `exprs` use, with the types that their uses
require.

Each name is declared, marked as inferred, in its home scope: the scope
that a declaration of the name would go in when the expression that uses
it was boxed. When the home scope already holds an inferred definition
of the name, that definition is narrowed instead. The type is the meet of
the types that the uses in `exprs` require, met with the type of that
inferred definition. The order of `exprs` does not change the result.

A name is not changed, and is reported in `skipped`, when the uses
require types that have no common subtype (`x + 1` and `x(3)`), when
they require no type, when the home scope holds a definition of the name
that is not inferred, and when the home scope is not the current scope
or one of its ancestors. Each expression then keeps the type that its
own uses require.

A library name used as a value (`N` in `N + 1`) is declared as a
variable, which shadows the library definition in the home scope. A
call head (`f` in `f(x)`) is declared with a function type.

####### exprs

readonly [`Expression`](#expression-5)[]

</MemberCard>

<MemberCard>

##### IComputeEngine.declareSequence() {#declaresequence}

```ts
declareSequence(name, def): IComputeEngine
```

Declare a sequence with a recurrence relation.

####### name

`string`

####### def

[`SequenceDefinition`](#sequencedefinition)

###### Example

```typescript
// Fibonacci sequence
ce.declareSequence('F', {
  base: { 0: 0, 1: 1 },
  recurrence: 'F_{n-1} + F_{n-2}',
});
ce.parse('F_{10}').evaluate();  // → 55
```

</MemberCard>

<MemberCard>

##### IComputeEngine.getSequenceStatus() {#getsequencestatus}

```ts
getSequenceStatus(name): SequenceStatus
```

Get the status of a sequence definition.

####### name

`string`

###### Example

```typescript
ce.parse('F_0 := 0').evaluate();
ce.getSequenceStatus('F');
// → { status: 'pending', hasBase: true, hasRecurrence: false, baseIndices: [0] }
```

</MemberCard>

<MemberCard>

##### IComputeEngine.getSequence() {#getsequence}

```ts
getSequence(name): SequenceInfo | undefined
```

Get information about a defined sequence.
Returns `undefined` if the symbol is not a sequence.

####### name

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.listSequences() {#listsequences}

```ts
listSequences(): string[]
```

List all defined sequences.
Returns an array of sequence names.

A name is listed when the definition it has in the current scope is a
sequence, as for `isSequence()`.

</MemberCard>

<MemberCard>

##### IComputeEngine.isSequence() {#issequence}

```ts
isSequence(name): boolean
```

Check if a symbol is a defined sequence.

The answer is for the definition that the name has in the current
scope. A sequence declared in an enclosing scope is a sequence. A
sequence is no longer one after the scope that declared it is popped,
or after `undeclare()`.

####### name

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.clearSequenceCache() {#clearsequencecache}

```ts
clearSequenceCache(name?): void
```

Clear the memoization cache for a sequence.
If no name is provided, clears caches for all sequences.

####### name?

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.getSequenceCache() {#getsequencecache}

```ts
getSequenceCache(name): 
  | Map<string | number, Expression>
  | undefined
```

Get the memoization cache for a sequence.
Returns a Map of index → value, or `undefined` if not a sequence or memoization is disabled.

For single-index sequences, keys are numbers.
For multi-index sequences, keys are comma-separated strings (e.g., '5,2').

####### name

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.getSequenceTerms() {#getsequenceterms}

```ts
getSequenceTerms(
   name, 
   start, 
   end, 
   step?): Expression[] | undefined
```

Generate a list of sequence terms from start to end (inclusive).

####### name

`string`

The sequence name

####### start

`number`

Starting index (inclusive)

####### end

`number`

Ending index (inclusive)

####### step?

`number`

Step size (default: 1)

###### Example

```typescript
ce.declareSequence('F', { base: { 0: 0, 1: 1 }, recurrence: 'F_{n-1} + F_{n-2}' });
ce.getSequenceTerms('F', 0, 10);
// → [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
```

</MemberCard>

<MemberCard>

##### IComputeEngine.lookupOEIS() {#lookupoeis}

```ts
lookupOEIS(terms, options?): Promise<OEISSequenceInfo[]>
```

Look up sequences in OEIS by their terms.

####### terms

(`number` \| [`Expression`](#expression-5))[]

Array of sequence terms to search for

####### options?

[`OEISOptions`](#oeisoptions)

Optional configuration (timeout, maxResults)

###### Example

```typescript
const results = await ce.lookupOEIS([0, 1, 1, 2, 3, 5, 8, 13]);
// → [{ id: 'A000045', name: 'Fibonacci numbers', ... }]
```

</MemberCard>

<MemberCard>

##### IComputeEngine.checkSequenceOEIS() {#checksequenceoeis}

```ts
checkSequenceOEIS(name, count?, options?): Promise<{
  matches: OEISSequenceInfo[];
  terms: number[];
}>
```

Check if a defined sequence matches an OEIS sequence.

####### name

`string`

Name of the defined sequence

####### count?

`number`

Number of terms to check (default: 10)

####### options?

[`OEISOptions`](#oeisoptions)

Optional configuration

###### Example

```typescript
ce.declareSequence('F', { base: { 0: 0, 1: 1 }, recurrence: 'F_{n-1} + F_{n-2}' });
const result = await ce.checkSequenceOEIS('F', 10);
// → { matches: [{ id: 'A000045', name: 'Fibonacci numbers', ... }], terms: [0, 1, 1, ...] }
```

</MemberCard>

<MemberCard>

##### IComputeEngine.interpret() {#interpret}

```ts
interpret(expr, options?): Promise<InterpretResult>
```

Interpret a notational expression, then propose OEIS-attributed closed
forms for it (the async v4 of the `Interpret` ladder).

`result.expression` is exactly what the synchronous `Interpret` head
returns (a `Sum`/`Product`, or the input unchanged); `result.candidates`
are OEIS-attributed closed forms, each verified to reproduce every
extracted sample exactly. This is the only interpretation path that
performs a network lookup. Too few samples, being offline, a timeout, or an
empty result all yield an empty candidate list rather than a rejection.

####### expr

[`Expression`](#expression-5)

The (typically inert, continuation-bearing) expression

####### options?

[`OEISOptions`](#oeisoptions)

OEIS request options (timeout, maxResults)

###### Example

```typescript
const { expression, candidates } = await ce.interpret(
  ce.parse('1 + 3 + 6 + 10 + \\cdots + n')
);
```

</MemberCard>

<MemberCard>

##### IComputeEngine.forget() {#forget}

```ts
forget(symbol?): void
```

####### symbol?

`string` \| `string`[]

</MemberCard>

<MemberCard>

##### IComputeEngine.undeclare() {#undeclare}

```ts
undeclare(names): void
```

Remove the binding of one or more names from the current scope.

The binding goes whatever it holds: a value, a function given with
`ce.assign()` or `ce.declare()`, or a function defined by one or more
clauses (`f(x) := …`, `DefineFunction`). This is different from
`forget()`, which removes assumptions and keeps the declaration.

After the call, the name is not declared in the current scope:

- When an enclosing scope declares the name, that declaration applies
  again. `undeclare()` does not change an enclosing scope.
- Otherwise, the name is a free symbol: `f(2)` stays unevaluated as
  `["f", 2]`, and `x + 1` stays symbolic.
- A later `ce.declare()`, `ce.assign()`, `f(x) := …` or `DefineFunction`
  of the name is a new declaration, and is accepted.

An expression boxed before the call does not use the removed binding
either. A symbol reads the value that the scope chain holds when the
expression is evaluated. A call such as `f(2)` boxed before the call
evaluates to `["f", 2]`, and after a new definition of `f` in the same
scope it uses the new definition, as for a function given again with
`ce.assign()`.

Assumptions about the name are not removed: an assumption applies to
the name, and so to a new declaration of it. Use `forget()` to remove
them.

####### names

`string` \| readonly `string`[]

###### Throws

if a name is not declared in the current scope. A name declared
only in an enclosing scope is not declared in the current scope. To
remove a name only when it is declared, test
`ce.context.lexicalScope.bindings.has(name)` first.

###### Throws

if a name is defined by a library: a standard library, a library
given to the constructor, or a library loaded with `ce.loadLibrary()`.
Also throws for any name of the system scope, which holds the standard
library.

###### Throws

if a name is the variable of an operator such as `Sum`, or a
parameter of a function, while that expression is evaluated.

When one name of a list is refused, no binding is removed.

```ts
ce.pushScope();
ce.parse('f(n) := n + 1').evaluate();
ce.parse('f(2)').evaluate();   // 3
ce.undeclare('f');
ce.parse('f(2)').evaluate();   // f(2)
```

</MemberCard>

<MemberCard>

##### IComputeEngine.ask() {#ask}

```ts
ask(pattern): BoxedSubstitution[]
```

####### pattern

[`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### IComputeEngine.verify() {#verify}

```ts
verify(query): boolean | undefined
```

####### query

`string` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### IComputeEngine.operatorInfo() {#operatorinfo-1}

```ts
operatorInfo(head): OperatorInfo | undefined
```

Introspect a registered operator head.

Returns `undefined` if no definition is registered in this engine.
Otherwise returns `{ kind, signature? }` where `kind` is `'function'`
when the operator has an `evaluate` or `collection` handler, and
`'opaque'` when it is declared as a typed-but-opaque node (e.g.,
`Triangle`, `Angle`).

Use this to classify heads encountered in parsed MathJSON without
maintaining a parallel list of "known" operators.

####### head

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.normalizeIdentifier() {#normalizeidentifier}

```ts
normalizeIdentifier(latex): string
```

Convert a LaTeX identifier string to its canonical MathJSON name without
declaring the symbol in the engine scope.

Examples:
- `'R_{3}'` → `'R_3'`
- `'\\theta_x'` → `'theta_x'`
- `'\\alpha'` → `'alpha'`
- `'1 + 2'` → `''` (not an identifier)

Use this instead of `ce.parse(latex).symbol` when you need the canonical
name without the side-effect of auto-declaring the symbol.

####### latex

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.symbolInfo() {#symbolinfo-1}

```ts
symbolInfo(name): SymbolInfo | undefined
```

Return introspection metadata for a symbol (value definition) in the
current scope chain.

- `kind: 'constant'` when the symbol is a CE-registered constant
  (e.g. `Pi`, `True`, `ExponentialE`).
- `kind: 'variable'` for declared but non-constant value symbols
  (e.g. after `ce.declare('a', 'real')`).

Returns `undefined` for unknown names and for names that resolve to
operator/function definitions (use `operatorInfo()` for those — the
two methods are non-overlapping).

####### name

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.searchDefinitions() {#searchdefinitions}

```ts
searchDefinitions(query, options?): DefinitionSearchResult[]
```

Reverse library search: map plain-text concept keywords to a ranked list
of matching identifiers in the current scope chain (standard library plus
any user declarations).

The query is a string (tokenized on whitespace) or an array of strings;
tokens are OR-ed — a definition matches when **any** token matches — and
definitions matching more tokens, or matching them more exactly, rank
higher.

Every returned `id` resolves via `ce.lookupDefinition(id)`; chain that
call for full detail.

####### query

`string` \| `string`[]

####### options?

####### limit?

`number`

</MemberCard>

<MemberCard>

##### IComputeEngine.suggestOperatorName() {#suggestoperatorname}

```ts
suggestOperatorName(name): string | undefined
```

Given a `name` that is **not** a known operator, return the closest known
operator name — a "did you mean" suggestion — or `undefined` when nothing
is close enough. Powers the Epsil `unknown-function` diagnostic.

Matching is conservative and applied in priority order (first match wins):
case-insensitive exact match, singular/plural, Damerau–Levenshtein
distance (≤ 2 for names of length ≥ 6, ≤ 1 for length 5, never for
shorter names), then a prefix match against exactly one operator. Ties
prefer the candidate sharing the longest prefix with the query.

```ts
ce.suggestOperatorName('Quartile'); // → 'Quartiles'
ce.suggestOperatorName('foo');      // → undefined
```

####### name

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.temporaryName() {#temporaryname}

```ts
temporaryName(hint, ...avoid): string
```

Return a name for a temporary symbol: `<hint>_tmp<n>`, with `n` the
smallest integer from 1 such that the name
- has no definition that `ce.lookupDefinition()` finds from the current
  scope, and
- is not a name of `avoid`, and does not occur in an expression of
  `avoid`, as a symbol (free or bound) or as the operator of a call.

Each item of `avoid` is a boxed expression, a string (one name, not text
to search) or a set of names. An array throws: an array of strings is
also a MathJSON call, so box it or pass the set of its names. An
expression is walked as it is written, each shared subtree once; the
walk does not enter the values or the bodies of the names it reads.

Pass in `avoid` every expression that the name will be put in or
combined with, the bodies and stored values that the computation reads,
and the names returned by earlier calls that are not declared yet: two
calls in a row with the same hint return the same name otherwise. A name
that an expression uses with no definition is not seen by the lookup.

The hint is cleaned: the `_` at its start and at its end are removed and
each `__` becomes `_`; `tmp` is used if nothing is left. A hint that is
not a valid symbol name, or for which `<hint>_tmp1` is not one (an
emoji), throws.

The function keeps no state and declares nothing: the same call in the
same state returns the same name. The caller declares the name if it
needs a definition, and the definition ends with its scope.

A name that ends with `_tmp` and a positive integer is reserved for this
function. The engine does not enforce it. A host can remove
`/_tmp[1-9]\d*$/` from the name to get the hint.

```ts
ce.temporaryName('t');                                // → 't_tmp1'
ce.temporaryName('t', ce.box(['Add', 't_tmp1', 'x'])); // → 't_tmp2'
ce.temporaryName('s', new Set(['s_tmp1']));           // → 's_tmp2'
ce.temporaryName('_x');                               // → 'x_tmp1'
```

####### hint

`string`

####### avoid

...(`string` \| `ReadonlySet`\<`string`\> \| [`Expression`](#expression-5))[]

</MemberCard>

<MemberCard>

##### IComputeEngine.functionProperties() {#functionproperties-1}

```ts
functionProperties(name): FunctionProperties | undefined
```

Return the known analytic properties of an operator — poles, zeros, branch
points/cuts, residues, holomorphic/meromorphic domains — drawn from the
Fungrim-derived metadata store, or `undefined` if none are recorded.

```ts
ce.functionProperties('Gamma')?.poles?.toString(); // 'NonPositiveIntegers'
```

The set-valued accessors (`poles`, `zeros`, ...) return a boxed set for the
unconditional record of that kind; parametric / conditional records (e.g.
residues that depend on parameters) are available via `entries`.

####### name

`string`

</MemberCard>

<MemberCard>

##### IComputeEngine.contourIntegrate() {#contourintegrate}

```ts
contourIntegrate(integrand, variable, contour): ContourIntegralResult
```

Integrate over a circle, simple polygon, or the entire real line by the
residue theorem. Real-line contours also accept an explicit principal value.
Returns pole classifications, residues, their sum, and the integral.
Unsupported or undecidable inputs have no value; boundary poles have
status `pole-on-contour`. See [ContourInput](#contourinput) for contour forms.

####### integrand

[`ExpressionInput`](#expressioninput)

####### variable

`string`

####### contour

[`ContourInput`](#contourinput)

</MemberCard>

<MemberCard>

##### IComputeEngine.toJSON() {#tojson-2}

```ts
toJSON(): string
```

Debug representation, e.g. for `JSON.stringify()`.

</MemberCard>

<MemberCard>

### RuleStep {#rulestep}

```ts
type RuleStep = KernelRuleStep<Expression>;
```

A single rule application step with provenance.

</MemberCard>

<MemberCard>

### RuleSteps {#rulesteps}

```ts
type RuleSteps = KernelRuleSteps<Expression>;
```

A list of rule application steps.

</MemberCard>

<MemberCard>

### ExplainStep {#explainstep}

```ts
type ExplainStep = KernelExplainStep<Expression>;
```

One step of an `Explanation`. See `expr.explain()`.

</MemberCard>

<MemberCard>

### Explanation {#explanation}

```ts
type Explanation = KernelExplanation<Expression>;
```

A structured step-by-step explanation. See `expr.explain()`.

</MemberCard>

<MemberCard>

### BoxedRule {#boxedrule}

```ts
type BoxedRule = KernelBoxedRule<Expression, IComputeEngine>;
```

A boxed/normalized rule form.

</MemberCard>

<MemberCard>

### BoxedRuleSet {#boxedruleset}

```ts
type BoxedRuleSet = KernelBoxedRuleSet<Expression, IComputeEngine>;
```

Collection of boxed rules.

</MemberCard>

<MemberCard>

### Scope {#scope-1}

```ts
type Scope = KernelScope<BoxedDefinition>;
```

Lexical scope specialized to boxed definitions.

</MemberCard>

<MemberCard>

### InspectableScope {#inspectablescope}

```ts
type InspectableScope = KernelInspectableScope<BoxedDefinition>;
```

A caller-owned, readable lexical scope — the product of
`ce.createScope()`. Specialized to boxed definitions.

</MemberCard>

<MemberCard>

### ScopeDeclaration {#scopedeclaration}

```ts
type ScopeDeclaration = KernelScopeDeclaration<BoxedDefinition>;
```

One entry of an [InspectableScope](#inspectablescope) harvest.

</MemberCard>

<MemberCard>

### ScopeNarrowing {#scopenarrowing}

```ts
type ScopeNarrowing = KernelScopeNarrowing<BoxedDefinition>;
```

One outer-definition narrowing observed by an [InspectableScope](#inspectablescope).

</MemberCard>

<MemberCard>

### EvalContext {#evalcontext}

```ts
type EvalContext = KernelEvalContext<Expression, BoxedDefinition, BoxedValueDefinition>;
```

Evaluation context specialized to this engine/runtime model.

</MemberCard>

### Expression {#expression-5}

#### Function Expression

<MemberCard>

##### Expression.operator {#operator-4}

```ts
readonly operator: string;
```

The name of the operator of the expression.

For example, the name of the operator of `["Add", 2, 3]` is `"Add"`.

A string literal has a `"String"` operator.

A symbol has a `"Symbol"` operator.

A number has a `"Number"`, `"Real"`, `"Rational"` or `"Integer"` operator; amongst some others.
Practically speaking, for fully canonical and valid expressions, all of these are likely to
collapse to `"Number"`.

</MemberCard>

#### Latex Parsing and Serialization

<MemberCard>

##### Expression.parseDiagnostics? {#parsediagnostics}

```ts
parseDiagnostics?: readonly ParseDiagnostic[];
```

Parse-time diagnostics collected when the expression was produced by
`ce.parse(latex, { diagnostics: true })`.

This property is present (as a possibly-empty, frozen array) **only** on
the top-level expression returned by a `diagnostics: true` parse; it is
`undefined` everywhere else (sub-expressions, and any expression parsed
without the flag). Diagnostics are purely additive metadata: enabling them
never changes the parse output.

See [ParseDiagnostic](#parsediagnostic) for the code enumeration and span conventions.

</MemberCard>

#### Numeric Expression

<MemberCard>

##### Expression.isEven {#iseven}

```ts
readonly isEven: boolean | undefined;
```

If the value of this expression is not an **integer** return `undefined`.

</MemberCard>

<MemberCard>

##### Expression.isOdd {#isodd}

```ts
readonly isOdd: boolean | undefined;
```

If the value of this expression is not an **integer** return `undefined`.

</MemberCard>

<MemberCard>

##### Expression.re {#re-2}

```ts
readonly re: number;
```

Return the real part of the value of this expression, if a number.

Otherwise, return `NaN` (not a number).

</MemberCard>

<MemberCard>

##### Expression.im {#im-2}

```ts
readonly im: number;
```

If value of this expression is a number, return the imaginary part of the
value. If the value is a real number, the imaginary part is 0.

Otherwise, return `NaN` (not a number).

</MemberCard>

<MemberCard>

##### Expression.bignumRe {#bignumre-1}

```ts
readonly bignumRe: BigDecimal | undefined;
```

If the value of this expression is a number, return the real part of the
value as a `BigNum`.

If the value is not available as a bignum return `undefined`. That is,
the value is not upconverted to a bignum.

To get the real value either as a bignum or a number, use
`expr.bignumRe ?? expr.re`.

When using this pattern, the value is returned as a bignum if available,
otherwise as a number or `NaN` if the value is not a number.

</MemberCard>

<MemberCard>

##### Expression.bignumIm {#bignumim-1}

```ts
readonly bignumIm: BigDecimal | undefined;
```

If the value of this expression is a number, return the imaginary part as
a `BigNum`.

It may be 0 if the number is real.

If the value of the expression is not a number or the value is not
available as a bignum return `undefined`. That is, the value is not
upconverted to a bignum.

To get the imaginary value either as a bignum or a number, use
`expr.bignumIm ?? expr.im`.

When using this pattern, the value is returned as a bignum if available, otherwise as a number or `NaN` if the value is not a number.

</MemberCard>

<MemberCard>

##### Expression.sgn {#sgn-3}

```ts
readonly sgn: Sign | undefined;
```

Return the sign of the expression.

Note that complex numbers have no natural ordering, so if the value is an
imaginary number (a complex number with a non-zero imaginary part),
`this.sgn` will return `unsigned`.

If a symbol, this does take assumptions into account, that is `this.sgn`
will return `positive` if the symbol is assumed to be positive
using `ce.assume()`.

Non-canonical expressions return `undefined`.

</MemberCard>

<MemberCard>

##### Expression.isPositive {#ispositive}

```ts
readonly isPositive: boolean | undefined;
```

The value of this expression is > 0, same as `isGreaterEqual(0)`

</MemberCard>

<MemberCard>

##### Expression.isNonNegative {#isnonnegative}

```ts
readonly isNonNegative: boolean | undefined;
```

The value of this expression is >= 0, same as `isGreaterEqual(0)`

</MemberCard>

<MemberCard>

##### Expression.isNegative {#isnegative}

```ts
readonly isNegative: boolean | undefined;
```

The value of this expression is &lt; 0, same as `isLess(0)`

</MemberCard>

<MemberCard>

##### Expression.isNonPositive {#isnonpositive}

```ts
readonly isNonPositive: boolean | undefined;
```

The  value of this expression is &lt;= 0, same as `isLessEqual(0)`

</MemberCard>

<MemberCard>

##### Expression.isNaN {#isnan-2}

```ts
readonly isNaN: boolean | undefined;
```

If true, the value of this expression is a number with no value: either
`NaN`.

`NaN` ("Not a Number", from the floating point format standard IEEE-754)
is the result of a computation with no value, such as `0.0/0.0` or
`0/0`, and the marker of an absent numeric operand.

Note that if `isNaN` is true, `isNumber` is also true (yes, `NaN` is a
number).

</MemberCard>

<MemberCard>

##### Expression.isInfinity {#isinfinity}

```ts
readonly isInfinity: boolean | undefined;
```

The numeric value of this expression is `±Infinity` or ComplexInfinity.

</MemberCard>

<MemberCard>

##### Expression.isFinite {#isfinite-1}

```ts
readonly isFinite: boolean | undefined;
```

This expression is a number, but not `±Infinity`, `ComplexInfinity` or
 `NaN`

</MemberCard>

#### Other

<MemberCard>

##### Expression.hash {#hash}

```ts
readonly hash: number;
```

A structural hash of this expression, suitable as an **in-memory**
bucketing or cache key with a deep compare on hit.

The contract:

- **Invariant**: if `a.isSame(b)` is `true`, then `a.hash === b.hash`.
  The hash is the structural tier's companion — a pure function of the
  canonical tree. A symbol's assigned value never affects it.

- **Stability**: deterministic within a release — the same canonical
  tree yields the same hash across engine instances and processes, as
  it is computed from structure and strings only, with no engine state.
  **Not stable across releases**: the hash function may change in any
  release, so a cache keyed on it must not outlive the engine build.
  Never persist it.

- **Collisions**: a 32-bit-class, bucketing-grade hash. Distinct
  expressions may share a hash; always verify a hash hit with
  `isSame()` (or another structural compare) before treating two
  expressions as identical.

- **Bound variables**: folds bound-variable _names_ (binding-identity,
  not alpha-equivalence), matching `isSame()`: `Sum(i, i in 1..n)` and
  `Sum(j, j in 1..n)` hash differently, just as they are not `isSame()`.
  This clause co-evolves with `isSame()` semantics.

- **Ranges and lists**: a finite `Range` whose bounds and step are
  integer literals and that has at most 10,000 elements is `isSame()` to
  the `List` of its integers, so it has the hash of that list:
  `Range(1, 3)` and `[1, 2, 3]` have the same hash. A character and a
  one-cluster string with the same content also have the same hash.

</MemberCard>

<MemberCard>

##### Expression.digest {#digest}

```ts
readonly digest: string;
```

A 128-bit digest of this expression's **serialized structure** — the
MathJSON `.json` writes — as 32 hexadecimal characters: an **in-memory
cache key** that needs no compare on hit, computed without writing the
MathJSON out.

It replaces `JSON.stringify(expr.json)` as a key, and keys the same
way: two expressions digest alike exactly when their MathJSON is the
same tree (a collision between two distinct trees is not expected in
practice — 128 bits from a non-cryptographic mixer, on the engine's own
serializations), with two deliberate exceptions where the digest is
coarser than the text — a dictionary's entry order does not enter it,
and a character digests like the one-cluster string with the same
content, as the two are the same value.

It is therefore **not an `isSame` key**, in both directions, and
`hash` remains the `isSame` companion:
- two symbols of the same name digest alike whatever they are bound to
  (a symbol serializes as its name), even when `isSame` — which reads
  binding identity — says they differ;
- the exact rational `1/2` and the float `0.5` are `isSame` but
  serialize apart, and digest apart.

- **Cost**: memoized per node, so it is linear in the DISTINCT nodes of
  the expression — except at and above a mutable object, whose record
  snapshot is read fresh like `.json`, so a store to it is seen by every
  node that contains it. `JSON.stringify(expr.json)` is
  linear in the PATHS, which on a value that shares its sub-expressions
  is exponential in the depth.
- **Stability**: deterministic within a release, across engine
  instances and processes. **Not stable across releases** and not
  cryptographic: never persist it, never use it to authenticate.
- **Bound variables**: folds bound-variable names, as the MathJSON does.

</MemberCard>

<MemberCard>

##### Expression.engine {#engine-2}

```ts
readonly engine: ComputeEngine;
```

The Compute Engine instance associated with this expression provides
a context in which to interpret it, such as definition of symbols
and functions.

</MemberCard>

<MemberCard>

##### Expression.toMathJson() {#tomathjson}

```ts
toMathJson(options?): MathJsonExpression
```

Serialize to a MathJSON expression with specified options.

Use `{ digits: 'auto' }` to round arbitrary-precision
numbers to `ce.precision` significant digits. The default
(`'max'`) emits all available digits with no rounding.

Use `{ objects }` to write a MathJSON expression of your own in place of
each object and mutable array (see `JsonSerializationOptions.objects`).

####### options?

`Readonly`\<`Partial`\<`JsonSerializationOptions`\<[`Expression`](#expression-5)\>\>\>

</MemberCard>

<MemberCard>

##### Expression.json {#json}

```ts
readonly json: MathJsonExpression;
```

MathJSON representation of this expression.

This representation always use shorthands when possible. Metadata is not
included.

Numbers are converted to JavaScript numbers and may lose precision.

The expression is represented exactly and no sugaring is applied. For
example, `["Power", "x", 2]` is not represented as `["Square", "x"]`.

For more control over the serialization, use `expr.toMathJson()`.

Note that lazy collections are *not* eagerly evaluated.

For arbitrary-precision numbers, the full raw `BigDecimal` value is
emitted with no rounding (same as `toJSON()`). This preserves data
fidelity for round-tripping but may include trailing digits beyond
`ce.precision` that are not meaningful. Use
`toMathJson({ digits: 'auto' })` for rounded output.

:::info[Note]
Applicable to canonical and non-canonical expressions.
:::

</MemberCard>

<MemberCard>

##### Expression.latex {#latex-1}

```ts
readonly latex: string;
```

Return a LaTeX representation of this expression.

This is a convenience getter that delegates to the standalone
`serialize()` function from the `latex-syntax` module.

Numeric values are rounded to `ce.precision` significant digits.
Noise digits from precision-bounded operations (division,
transcendentals) are not displayed.

</MemberCard>

<MemberCard>

##### Expression.toLatex() {#tolatex}

```ts
toLatex(options?): string
```

Return a LaTeX representation of this expression with custom
serialization options.

Numeric values are rounded to `ce.precision` significant digits.

####### options?

`Record`\<`string`, `any`\>

</MemberCard>

<MemberCard>

##### Expression.print() {#print-1}

```ts
print(): void
```

Output to the console a string representation of the expression.

Note that lazy collections are eagerly evaluated when printed.

</MemberCard>

<MemberCard>

##### Expression.verbatimLatex? {#verbatimlatex}

```ts
verbatimLatex?: string;
```

If the expression was constructed from a LaTeX string, the verbatim LaTeX
 string it was parsed from.

</MemberCard>

<MemberCard>

##### Expression.sourceOffsets? {#sourceoffsets-2}

```ts
sourceOffsets?: [start: number, end: number];
```

Source offsets in the original source string, when available.

</MemberCard>

<MemberCard>

##### Expression.isCanonical {#iscanonical}

If `true`, this expression is in a canonical form.

</MemberCard>

<MemberCard>

##### Expression.isStructural {#isstructural}

If `true`, this expression is in a structural form.

The structural form of an expression is used when applying rules to
an expression. For example, a rational number is represented as a
function expression instead of a `Expression` object.

</MemberCard>

<MemberCard>

##### Expression.canonical {#canonical-1}

Return the canonical form of this expression.

If a function expression or symbol, they are first bound with a definition
in the current scope.

When determining the canonical form the following operator definition
flags are applied:
- `associative`: \\( f(a, f(b), c) \longrightarrow f(a, b, c) \\)
- `idempotent`: \\( f(f(a)) \longrightarrow f(a) \\)
- `involution`: \\( f(f(a)) \longrightarrow a \\)
- `commutative`: sort the arguments.

If this expression is already canonical, the value of canonical is
`this`.

The arguments of a canonical function expression may not all be
canonical, for example in the `["Declare", "i", 2]` expression,
`i` is not canonical since it is used only as the name of a symbol, not
as a (potentially) existing symbol.

:::info[Note]
Partially canonical expressions, such as those produced through
`CanonicalForm`, also yield an expression which is marked as `canonical`.
This means that, likewise for partially canonical expressions, the
`canonical` property will return the self-same expression (and
'isCanonical' will also be true).
:::

</MemberCard>

<MemberCard>

##### Expression.structural {#structural}

Return the structural form of this expression.

Some expressions, such as rational numbers, are represented with
a `Expression` object. In some cases, for example when doing a
structural comparison of two expressions, it is useful to have a
structural representation of the expression where the rational numbers
is represented by a function expression instead.

If there is a structural representation of the expression, return it,
otherwise return `this`.

</MemberCard>

<MemberCard>

##### Expression.isValid {#isvalid}

```ts
readonly isValid: boolean;
```

`false` if this expression or any of its subexpressions is an `["Error"]`
expression.

The check is **deep**: an `["Error"]` anywhere in the expression tree
invalidates the whole expression. This includes the *elements* of a list,
vector or matrix — `(1,2) + [3,4]` broadcasts to a list of
`incompatible-type` errors, and that list is invalid — and operands held
unevaluated, such as the body of a `["Hold"]`.

:::info[Note]
Applicable to canonical and non-canonical expressions. For
non-canonical expression, this may indicate a syntax error while parsing
LaTeX. For canonical expression, this may indicate argument type
mismatch, or missing or unexpected arguments.
:::

This is a check for **well-formedness, not for meaningfulness**: it
answers "is this expression free of errors?", not "will it evaluate to a
useful value?". An expression is still valid when it contains free
symbols (`x + 1`), calls an undeclared function, or evaluates to `NaN` or
`±∞` (`0/0` and `1/0` are both valid). Conversely, a valid expression may
still fail to evaluate for reasons this property does not report.

Use it as an **admission gate** — check `isValid` before compiling,
plotting, or otherwise consuming an expression built from untrusted or
user-supplied input, since malformed input surfaces as an `["Error"]`
expression rather than as a thrown exception. To find out *what* is
wrong, walk the expression for `["Error"]` subexpressions; each carries
an error code and the offending operand.

</MemberCard>

<MemberCard>

##### Expression.isPure {#ispure}

```ts
readonly isPure: boolean;
```

If *true*, evaluating this expression has no side-effects (does not
change the state of the Compute Engine).

If *false*, evaluating this expression may change the state of the
Compute Engine or it may return a different value each time it is
evaluated, even if the state of the Compute Engine is the same.

As an example, the `["Add", 2, 3]` function expression is pure, but
the `["Random"]` function expression is not pure.

For a function expression to be pure, the function itself (its operator)
must be pure, and all of its arguments must be pure too.

A pure function expression may return a different value each time it is
evaluated if its arguments are not constant. For example, the
`["Add", "x", 1]` function expression is pure, but it is not
constant, because `x` is not constant.

:::info[Note]
Applicable to canonical expressions only
:::

Since Stage 2 of the effects model this is a **view** of the runtime
effect channel: "no impurity label in `effectsOf(expr)`" (see
`boxed-expression/effects-of.ts`).

</MemberCard>

<MemberCard>

##### Expression.effects {#effects-4}

```ts
readonly effects: 
  | "any"
  | readonly EffectLabel[]
  | undefined;
```

The effects of **evaluating** this expression: `undefined` when there are
none (the expression is pure), `'any'` when the effects are not known, or
the effect labels in alphabetical order.

This is the set `isPure` summarizes — `isPure` is "no impurity label in
here" — but it says *which* effects, so a consumer can act on them: a
`scope` write invalidates a memo, `random` means the value will differ on
re-evaluation, `network` means evaluating may be slow or may fail.

It reports what evaluating this expression **does**, not what the value it
produces **can do** if you later invoke it. A symbol bound to a drawing
function has no effects — evaluating it just yields the function — while
its *type* carries the draw:

```ts
ce.assign('rf', ce.box(['Function', ['Random'], 'x']));
ce.box('rf').effects;           // ➔ undefined  (producing the value)
ce.box('rf').isPure;            // ➔ true
ce.box('rf').type.effects;      // ➔ ['random'] (invoking it)
ce.box(['Map', xs, 'rf']).effects; // ➔ ['random'] (Map invokes it)
```

Numbers, strings, symbols and dictionaries have no effects. See
`docs/EFFECTS-MODEL.md` ("Projection and discharge") for how an
application's effects are computed from its operator and operands.

</MemberCard>

<MemberCard>

##### Expression.isConstant {#isconstant-1}

```ts
readonly isConstant: boolean;
```

`True` if evaluating this expression always returns the same value.

If *true* and a function expression, implies that it is *pure* and
that all of its arguments are constant.

Number literals, symbols with constant values, and pure numeric functions
with constant arguments are all *constant*, i.e.:
- `42` is constant
- `Pi` is constant
- `["Divide", "Pi", 2]` is constant
- `x` is not constant, unless declared with a constant flag.
- `["Add", "x", 2]` is either constant only if `x` is constant.

</MemberCard>

<MemberCard>

##### Expression.errors {#errors}

```ts
readonly errors: readonly Expression[];
```

All the `["Error"]` subexpressions.

If an expression includes an error, the expression is also an error.
In that case, the `this.isValid` property is `false`.

:::info[Note]
Applicable to canonical and non-canonical expressions.
:::

</MemberCard>

<MemberCard>

##### Expression.getSubexpressions() {#getsubexpressions}

```ts
getSubexpressions(operator): readonly Expression[]
```

All the subexpressions matching the named operator, recursively.

Example:

```js
const expr = ce.parse('a + b * c + d');
const subexpressions = expr.getSubexpressions('Add');
// -> `[['Add', 'a', 'b'], ['Add', 'c', 'd']]`
```

The walk continues into the values of a dictionary. A function
expression or a dictionary that occurs several times as the SAME object
(a shared subexpression) is listed once.

:::info[Note]
Applicable to canonical and non-canonical expressions.
:::

####### operator

`string`

</MemberCard>

<MemberCard>

##### Expression.subexpressions {#subexpressions}

```ts
readonly subexpressions: readonly Expression[];
```

All the subexpressions in this expression, recursively

Example:

```js
const expr = ce.parse('a + b * c + d');
const subexpressions = expr.subexpressions;
// -> `[['Add', 'a', 'b'], ['Add', 'c', 'd'], 'a', 'b', 'c', 'd']`
```

The walk continues into the values of a dictionary. A function
expression or a dictionary that occurs several times as the SAME object
(a shared subexpression) is listed once.

:::info[Note]
Applicable to canonical and non-canonical expressions.
:::

</MemberCard>

<MemberCard>

##### Expression.symbols {#symbols}

```ts
readonly symbols: readonly string[];
```

All the symbols in the expression, recursively, including
bound variables (e.g., summation/product index variables).

Use [unknowns](#unknowns) or [freeVariables](#freevariables) to get only the
symbols that are free (not bound by a scoping construct).

```js
const expr = ce.parse('a + b * c + d');
const symbols = expr.symbols;
// -> ['a', 'b', 'c', 'd']
```

:::info[Note]
Applicable to canonical and non-canonical expressions.
:::

</MemberCard>

<MemberCard>

##### Expression.unknowns {#unknowns}

```ts
readonly unknowns: readonly string[];
```

All the symbols used in the expression that do not have a value
associated with them, i.e. they are declared but not defined.

</MemberCard>

<MemberCard>

##### Expression.freeVariables {#freevariables}

```ts
readonly freeVariables: readonly string[];
```

The free variables of the expression: symbols that are not constants,
not operators, not bound to a value, and not locally scoped (e.g.,
summation/product index variables are excluded).

This is an alias for [unknowns](#unknowns).

</MemberCard>

<MemberCard>

##### Expression.defines {#defines}

```ts
readonly defines: readonly string[];
```

The symbols **defined** by this expression: the target of a top-level
`["Assign", …]` or `["Declare", …]` (e.g. `a` in `a := 3`, `f` in
`f(x) := …`), recursing through `["Block", …]` sequences. A
destructuring target defines each name of its pattern: `a` and `b` in
`(a, b) := (1, 2)`. Empty for expressions that define nothing.

Complements [freeVariables](#freevariables) (the symbols an expression
*references*). A tool that builds a dependency graph keyed on cells —
e.g. a notebook — can use `defines` for the out-edges and
[references](#references) for the in-edges.

:::info[Note]
Applicable to canonical and non-canonical expressions.
:::

</MemberCard>

<MemberCard>

##### Expression.referencedFunctions {#referencedfunctions}

```ts
readonly referencedFunctions: readonly string[];
```

The user functions **applied** in this expression: the operator head of
a function application when that head is a user-definable symbol — `f` in
`f(x)`, `g` in `g(x) := f(x) + 1`. A user function is listed whether it
is undefined, declared, or already defined (`f(x) := …`,
`ce.assign("f", …)`). The operators of a library (`Add`, `Sin`, …: the
standard library, a library given to the constructor, or one loaded with
`ce.loadLibrary()`), constants, and names bound by an enclosing scope of
the expression (function parameters, summation indices, `Block` locals) are
excluded.

Operator heads are not symbols of the expression, so they appear in
neither [symbols](#symbols) nor [freeVariables](#freevariables). This accessor recovers
the function-call dependency edges those views miss.

:::info[Note]
Applicable to canonical and non-canonical expressions.
:::

</MemberCard>

<MemberCard>

##### Expression.references {#references}

```ts
readonly references: readonly string[];
```

The symbols this expression **references** but does not itself define:
every user name it reads, as a value or as an applied function
([referencedFunctions](#referencedfunctions)), minus [defines](#defines). A name is listed
whether or not it already has a value or a definition: after
`a := 5`, `g(x) := x + a` still references `a`. This is the difference
with [freeVariables](#freevariables), which lists only the symbols that have no
value. The names of a library (`Pi`, `Sin`, …: the standard library, a
library given to the constructor, or one loaded with
`ce.loadLibrary()`), constants, and names bound by the expression itself (parameters, indices, `Block`
locals) are excluded.

This is the complete in-edge set for a dependency graph keyed on cells
(e.g. a notebook): pair it with [defines](#defines) for the out-edges.
Subtracting `defines` drops self-references, so a recursive
`g(x) := g(x - 1)` reports no dependency on itself.

```js
const cell = ce.parse('g(x) := f(x) + a', { canonical: false });
cell.defines;    // -> ['g']
cell.references; // -> ['a', 'f']
```

:::info[Note]
Applicable to canonical and non-canonical expressions.
:::

</MemberCard>

<MemberCard>

##### Expression.toNumericValue() {#tonumericvalue}

```ts
toNumericValue(): [NumericValue, Expression]
```

Attempt to factor a numeric coefficient `c` and a `rest` out of a
canonical expression such that `rest.mul(c)` is equal to `this`.

Attempts to make `rest` a positive value (i.e. pulls out negative sign).

```json
['Multiply', 2, 'x', 3, 'a']
   -> [NumericValue(6), ['Multiply', 'x', 'a']]

['Divide', ['Multiply', 2, 'x'], ['Multiply', 3, 'y', 'a']]
   -> [NumericValue({rational: [2, 3]}), ['Divide', 'x', ['Multiply, 'y', 'a']]]
```

</MemberCard>

<MemberCard>

##### Expression.neg() {#neg-2}

```ts
neg(): Expression
```

Negate (additive inverse)

</MemberCard>

<MemberCard>

##### Expression.inv() {#inv-1}

```ts
inv(): Expression
```

Inverse (multiplicative inverse)

</MemberCard>

<MemberCard>

##### Expression.abs() {#abs-1}

```ts
abs(): Expression
```

Absolute value

</MemberCard>

<MemberCard>

##### Expression.add() {#add-4}

```ts
add(rhs): Expression
```

Addition

####### rhs

`number` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.sub() {#sub-2}

```ts
sub(rhs): Expression
```

Subtraction

####### rhs

[`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.mul() {#mul-2}

```ts
mul(rhs): Expression
```

Multiplication

####### rhs

  \| `number`
  \| [`NumericValue`](#abstract-numericvalue)
  \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.div() {#div-2}

```ts
div(rhs): Expression
```

Division

####### rhs

`number` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.pow() {#pow-2}

```ts
pow(exp): Expression
```

Power

####### exp

`number` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.root() {#root-1}

```ts
root(exp): Expression
```

Exponentiation

####### exp

`number` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.sqrt() {#sqrt-1}

```ts
sqrt(): Expression
```

Square root

</MemberCard>

<MemberCard>

##### Expression.ln() {#ln-1}

```ts
ln(base?): Expression
```

Logarithm (natural by default)

####### base?

`number` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.numerator {#numerator-1}

Return this expression expressed as a numerator.

</MemberCard>

<MemberCard>

##### Expression.denominator {#denominator-1}

Return this expression expressed as a denominator.

</MemberCard>

<MemberCard>

##### Expression.numeratorDenominator {#numeratordenominator}

Return this expression expressed as a numerator and denominator.

</MemberCard>

<MemberCard>

##### Expression.toRational() {#torational}

```ts
toRational(): [number, number] | null
```

Return the value of this expression as a pair of integer numerator and
denominator, or `null` if the expression is not a rational number.

- For a `BoxedNumber` with an exact rational value, extracts from the
  numeric representation.
- For an integer, returns `[n, 1]`.
- For a `Divide` or `Rational` function with integer operands, returns
  `[num, den]`.
- For everything else, returns `null`.

The returned rational is always in lowest terms.

```typescript
ce.parse('\\frac{6}{4}').toRational()  // [3, 2]
ce.parse('7').toRational()              // [7, 1]
ce.parse('x + 1').toRational()          // null
ce.number(1.5).toRational()             // null (machine float)
```

</MemberCard>

<MemberCard>

##### Expression.factors() {#factors}

```ts
factors(): readonly Expression[]
```

Return the multiplicative factors of this expression as a flat array.

This is a structural decomposition — it does not perform algebraic
factoring (use `ce.function('Factor', [expr])` for that).

- `Multiply(a, b, c)` returns `[a, b, c]`
- `Negate(x)` returns `[-1, ...x.factors()]`
- Anything else returns `[expr]`

```typescript
ce.parse('2xyz').factors()     // [2, x, y, z]
ce.parse('-3x').factors()      // [-1, 3, x]
ce.parse('x + 1').factors()    // [x + 1]
```

</MemberCard>

<MemberCard>

##### Expression.polynomialCoefficients() {#polynomialcoefficients}

```ts
polynomialCoefficients(variable?): readonly Expression[] | undefined
```

Return the coefficients of this expression as a polynomial in `variable`,
in descending order of degree. Returns `undefined` if the expression is
not a polynomial in the given variable.

If `variable` is omitted, auto-detects when the expression has exactly
one unknown. Returns `undefined` if there are zero or multiple unknowns.

```typescript
ce.parse('x^2 + 2x + 1').polynomialCoefficients('x')  // [1, 2, 1]
ce.parse('x^3 + 2x + 1').polynomialCoefficients('x')  // [1, 0, 2, 1]
ce.parse('sin(x)').polynomialCoefficients('x')          // undefined
ce.parse('x^2 + 5').polynomialCoefficients()            // [1, 0, 5]
```

Subsumes `isPolynomial`:
```typescript
const isPolynomial = expr.polynomialCoefficients('x') !== undefined;
```

Subsumes `polynomialDegree`:
```typescript
const degree = expr.polynomialCoefficients('x')?.length - 1;
```

When `variable` is an array, the expression must be polynomial in ALL
listed variables. Coefficients are decomposed by the first variable;
remaining variables appear as symbolic coefficients.

```typescript
ce.parse('x^2*y + 3x + y^2').polynomialCoefficients(['x', 'y'])
// → [y, 3, y²]  (coefficients of x², x¹, x⁰)
```

####### variable?

`string` \| `string`[]

</MemberCard>

<MemberCard>

##### Expression.polynomialRoots() {#polynomialroots}

```ts
polynomialRoots(variable?): readonly Expression[] | undefined
```

Return the roots of this expression treated as a polynomial in `variable`.
Returns `undefined` if the expression is not a polynomial in the given
variable. Returns an empty array if no roots can be found.

If `variable` is omitted, auto-detects when the expression has exactly
one unknown.

```typescript
ce.parse('x^2 - 5x + 6').polynomialRoots('x')  // [2, 3]
ce.parse('x^2 + 1').polynomialRoots('x')         // [] (no real roots)
ce.parse('sin(x)').polynomialRoots('x')           // undefined
```

####### variable?

`string`

</MemberCard>

<MemberCard>

##### Expression.isScoped {#isscoped}

```ts
readonly isScoped: boolean;
```

If true, the expression has its own local scope that can be used
for local variables and arguments. Only true if the expression is a
function expression.

</MemberCard>

<MemberCard>

##### Expression.localScope {#localscope}

If this expression has a local scope, return it.

</MemberCard>

<MemberCard>

##### Expression.subs() {#subs}

```ts
subs(sub, options?): Expression
```

Replace all the FREE occurrences of the symbols in the expression as
indicated.

The occurrences replaced are exactly those that `freeVariables` reports
as free. A name bound by a binder is not replaced where the binder binds
it: the index of a `Sum`, `Product` or `Comprehension`, the parameter of
a `Function` literal, the variable of a definite `Integrate`, a local of
a `Block`. So `["Sum", "j", ["Limits", "j", 1, 3]]` is unchanged by
`subs({j: 5})`, and in `["Add", "j", ["Sum", "j", ["Limits", "j", 1, 3]]]`
only the first `j` is replaced. The bounds of a `Limits` clause of a
`Sum`, `Product` or `Integrate` read the enclosing binding, so they are
replaced: `["Sum", "j", ["Limits", "j", 1, "j"]]` with `j` replaced by
`4` is `["Sum", "j", ["Limits", "j", 1, 4]]`.

The variable of `D`, the expansion variable of `Series` and the variable
of an indefinite `Integrate` are free: the value of the expression is a
function of them. When such a variable is replaced, the expression keeps
its variable, and the result is the value of the expression at the
point: `["D", ["Power", "x", 2], "x"]` with `x` replaced by `3` is
`["EvaluateAt", ["Function", ["D", ["Power", "x", 2], "x"], "x"], 3]`,
written `\left.\left(\frac{\mathrm{d}x^2}{\mathrm{d}x}\right)\right|_{x=3}`,
which evaluates to `6`. Only the variable itself is applied at a
point. The replacement of another name is put in the derivative, the
series or the integral before it is computed: `["D", ["Multiply", "y",
["Power", "x", 2]], "x"]` with `y` replaced by `3` is `["D",
["Multiply", 3, ["Power", "x", 2]], "x"]`, and `["D", ["Multiply", "x",
"y"], "x"]` with `y` replaced by `x` is `["D", ["Multiply", "x", "x"],
"x"]`, which evaluates to `2x`. When more than one such variable is
replaced, the `Function` literal has one parameter per variable, the
point is a `Tuple`, and all the variables are replaced at the same time:
`\left.\left(…\right)\right|_{x=3, y=5}`. A replacement can contain the
variable: with `x` replaced by `x + 1`, the `D` above evaluates to
`2(x + 1)`, where the `x` of `x + 1` is the `x` of the enclosing scope.
When the value has no
closed form (`Series(e^{1/x}, x, 0, 3)`), the `EvaluateAt` stays
unevaluated. The value of a `Series` at a point keeps its remainder:
`Series(sin x, x, 0, 3)` with `x` replaced by `1/2` evaluates to
`23/48 + BigO(1/32)`, and with `x` replaced by `0` to `BigO(0)`. Under
`.N()` the remainder stays a `BigO` term and the other terms are
approximated: the first value is `0.479… + BigO(0.03125)`. Wrap the
series in `Normal` to drop the remainder, before or after the
substitution. `Normal(Series(sin x, x, 0, 3))` with `x` replaced by
`0.5` evaluates to `0.479…` under `.N()`.

A `Block` that assigns a variable of an enclosing scope, and can read it
before the first assignment, reads its value from outside the block, so
the variable is free. A replacement of each occurrence would give an
invalid assignment, so the block keeps its occurrences and gets a first
statement that assigns the replacement: with `a` declared outside the
block, `["Block", ["Assign", "a", ["Add", "a", 1]], "a"]` with `a`
replaced by `2` is `["Block", ["Assign", "a", 2], ["Assign", "a", ["Add",
"a", 1]], "a"]`, which evaluates to `3`. When it is evaluated, the block
writes the variable of the enclosing scope, as the block it replaces
does. With several such variables, the first statement assigns them all
at the same time: `["Assign", ["Tuple", "a", "b"], ["Tuple", "b",
"a"]]` for `a` replaced by `b` and `b` replaced by `a`. A replacement of
another name that reads such a variable (`x` replaced by `a` with `a`
replaced by `3`) is inserted as it is, and reads the value that the
first statement assigns.

The substitution avoids variable capture. When a replacement contains a
free name that a binder binds, and the substitution replaces an
occurrence in the scope of that name, the binder renames the name to a
fresh name first: `k` becomes `k_1`, or `k_2` when `k_1` is used in the
binder or in a replacement.
`["Sum", ["Add", "j", "k"], ["Limits", "k", 1, 3]]` with `j` replaced by
`k` is `["Sum", ["Add", "k", "k_1"], ["Limits", "k_1", 1, 3]]`, which
evaluates to `3k + 6`, and `["Function", ["Power", "y", "x"], "x"]` with
`y` replaced by `x` is the function `x_1 ↦ x^(x_1)`. A named argument of a
call of such a renamed function uses the new name of the parameter. A
binder with no such name is not renamed and keeps its identity.

In two cases a bound name cannot be renamed before the block runs, and
the replacement is inserted as it is, so the held block captures the
name:
- the target of an `Assign` in a `Block` that is not canonical (a held
  block), when no `Declare` of the block declares it. The `Assign` makes
  a local only when the name is not declared where the block is released.
  With `s` declared, `["Hold", ["Block", ["Assign", "s", 3], ["Add", "y",
  "s"]]]` with `y` replaced by `s` is `["Hold", ["Block", ["Assign", "s",
  3], ["Add", "s", "s"]]]`, and its released value is `6`;
- a `Declare` or an `Assign` in an operand of a statement of a held
  block (a branch of an `If`): the later reads denote the local only when
  that branch runs.

The replacement is also inserted as it is in a few other rare cases
where a correct rename cannot be decided before the expression runs.

`this.replace()` can give a similar result, and it can replace more
than symbols, but `this.subs()` is more efficient and simpler. A
recursive `replace()` does not skip bound variables and does not rename
a binder: it rewrites the structure of the expression. A rule whose
match is the symbol `j` replaces the `j` of
`["Sum", ["Add", "j", "k"], ["Limits", "k", 1, 3]]` by `k` with no
rename, and its result evaluates to `12`. The values of the wildcards of
a rule are inserted in its replacement the same way: a binder that the
replacement writes binds the names in them.

The free symbols of the result are bound in the CURRENT scope, not in the
scope the receiver was built in. A node that owns a local scope keeps
that scope, so a binder's bound variables go on denoting the binder's own
bindings — including for a binder nested inside another one, whose scope
chain would otherwise no longer reach the outer binder's index.

If `options.canonical` is not set, the result is canonical if `this`
is canonical.

:::info[Note]
Applicable to canonical and non-canonical expressions.

If this is a function, an empty substitution is given, and the computed value of `canonical`
does not differ from that of this expr.: then a call this method is analagous to requesting a
*clone*.
:::

####### sub

`Substitution`\<[`ExpressionInput`](#expressioninput)\>

####### options?

####### canonical?

[`CanonicalOptions`](#canonicaloptions)

</MemberCard>

<MemberCard>

##### Expression.map() {#map}

```ts
map(fn, options?): Expression
```

Recursively replace all the subexpressions in the expression as indicated.

To remove a subexpression, return an empty `["Sequence"]` expression.

The `canonical` option is applied to each function subexpression after
the substitution is applied.

If no `options.canonical` is set, the result is canonical if `this`
is canonical.

**Default**: `{ canonical: this.isCanonical, recursive: true }`

:::info[Note]
Applicable to canonical and non-canonical expressions.
:::

####### fn

(`expr`) => [`Expression`](#expression-5)

####### options?

####### canonical

[`CanonicalOptions`](#canonicaloptions)

####### recursive?

`boolean`

</MemberCard>

<MemberCard>

##### Expression.replace() {#replace}

```ts
replace(rules, options?): Expression | null
```

Transform the expression by applying one or more replacement rules:

- If the expression matches the `match` pattern and the `condition`
 predicate is true, replace it with the `replace` pattern.

- If no rules apply, return `null`.

The `form` option controls the form of *replacements*. The deprecated
`canonical` option is also accepted for backward compatibility; only one
of the two may be specified.

When neither `form` nor `canonical` is specified, the form of each
replacement is determined as follows:
1. the form of the replacement produced by the rule, if it has a
   non-`'raw'` form;
2. otherwise, the form of the expression being replaced;
3. otherwise, the replacement is left in its raw form.

While the form applies directly to replaced sub-expressions only, a
non-`'raw'` form also propagates 'opportunistically' up the expression
tree: an expression whose operands all share a form after replacement
assumes that form as well. (Specifying `form: 'raw'` disables this
propagation.)

:::info[Note]
Applicable to input expressions of any form.

To match a specific symbol (not a wildcard pattern), the `match` must be
a `Expression` (e.g., `{ match: ce.expr('x'), replace: ... }`).

For simple symbol substitution, consider using `subs()` instead.
:::

####### rules

`BoxedRuleSet` \| `Rule` \| `Rule`[]

####### options?

`Partial`\<[`ReplaceOptions`](#replaceoptions)\>

</MemberCard>

<MemberCard>

##### Expression.has() {#has}

```ts
has(v): boolean
```

True if the expression includes a symbol `v` or a function operator `v`.

When `v` is an array, true if the expression includes any of the names
in `v`.

A dictionary is a node with the operator `Dictionary`, and the test
looks at the values of its entries. A key is a string, not a symbol, so
a key never matches: for `{"a" -> u}`, `has("u")` and
`has("Dictionary")` are `true` and `has("a")` is `false`. To test
whether a dictionary has a key, use `hasKey()` of
`DictionaryInterface`.

:::info[Note]
Applicable to canonical and non-canonical expressions.
:::

####### v

`string` \| `string`[]

</MemberCard>

<MemberCard>

##### Expression.match() {#match-1}

```ts
match(pattern, options?): BoxedSubstitution<Expression> | null
```

If this expression matches `pattern`, return a substitution that makes
`pattern` equal to `this`. Otherwise return `null`.

If `pattern` includes wildcards (symbols that start
with `_`), the substitution will include a prop for each matching named
wildcard.

If this expression matches `pattern` but there are no named wildcards,
return the empty substitution, `{}`.

`pattern` can be:
- A **string** (LaTeX): single-character symbols are auto-converted to
  wildcards (e.g., `'ax^2+bx+c'` treats `a`, `b`, `c` as wildcards).
  Results use unprefixed keys (`{a: 3}` not `{_a: 3}`) and self-matches
  are filtered out. `useVariations` and `matchMissingTerms` default to
  `true`. Unprefixed keys are accepted in `substitution`.
- A **MathJSON array** (e.g., `['Add', '_a', '_b']`): boxed automatically.
- An **Expression**: used directly.

Read more about [**patterns and rules**](/compute-engine/guides/patterns-and-rules/).

:::info[Note]
Applicable to canonical and non-canonical expressions.
:::

####### pattern

[`ExpressionInput`](#expressioninput)

####### options?

`PatternMatchOptions`\<[`Expression`](#expression-5)\>

</MemberCard>

<MemberCard>

##### Expression.wikidata {#wikidata-1}

```ts
readonly wikidata: string | undefined;
```

Wikidata identifier.

If not a canonical expression, return `undefined`.

</MemberCard>

<MemberCard>

##### Expression.description {#description-2}

```ts
readonly description: string[] | undefined;
```

An optional short description if a symbol or function expression.

May include markdown. Each string is a paragraph.

If not a canonical expression, return `undefined`.

</MemberCard>

<MemberCard>

##### Expression.url {#url-3}

```ts
readonly url: string | undefined;
```

An optional URL pointing to more information about the symbol or
 function operator.

If not a canonical expression, return `undefined`.

</MemberCard>

<MemberCard>

##### Expression.complexity {#complexity-1}

```ts
readonly complexity: number | undefined;
```

Expressions with a higher complexity score are sorted
first in commutative functions

If not a canonical expression, return `undefined`.

</MemberCard>

<MemberCard>

##### Expression.baseDefinition {#basedefinition-1}

```ts
readonly baseDefinition: BoxedBaseDefinition | undefined;
```

For symbols and functions, a definition associated with the
expression. `this.baseDefinition` is the base class of symbol and function
definition.

If not a canonical expression, return `undefined`.

</MemberCard>

<MemberCard>

##### Expression.operatorDefinition {#operatordefinition-1}

```ts
readonly operatorDefinition: BoxedOperatorDefinition | undefined;
```

For function expressions, the definition of the operator associated with
the expression. For symbols, the definition of the symbol if it is an
operator, for example `"Sin"`.

If not a canonical expression or not a function expression,
its value is `undefined`.

</MemberCard>

<MemberCard>

##### Expression.valueDefinition {#valuedefinition-1}

```ts
readonly valueDefinition: BoxedValueDefinition | undefined;
```

For symbols, a definition associated with the expression, if it is
not an operator.

If not a canonical expression, or not a value, its value is `undefined`.

</MemberCard>

<MemberCard>

##### Expression.simplify() {#simplify}

```ts
simplify(options?): Expression
```

Return a simpler form of this expression.

A series of rewriting rules are applied repeatedly, until no more rules
apply.

The values assigned to symbols and the assumptions about symbols may be
used, for example `expr.isInteger` or `expr.isPositive`.

No calculations involving decimal numbers (numbers that are not
integers) are performed but exact calculations may be performed,
for example:

$$ \sin(\frac{\pi}{4}) \longrightarrow \frac{\sqrt{2}}{2} $$.

The result is canonical.

To manipulate symbolically non-canonical expressions, use `expr.replace()`.

####### options?

`Partial`\<`SimplifyOptions`\>

</MemberCard>

<MemberCard>

##### Expression.explain() {#explain}

```ts
explain(operation?, options?): Explanation
```

Return a structured, step-by-step explanation of an operation applied
to this expression: the textbook chain *expression → step (with a
reason) → … → result*.

The `operation` defaults to `'simplify'`. The explanation runs the same
engine code as the plain method: `explain('simplify').result` is the
same value `simplify()` returns.

For `'solve'`, the receiver is a univariate equation (or an expression
`f`, read as `f = 0`); the unknown is inferred or passed via
`options.variable`. Step values are *equations* — the state after each
phase (`2x+1=5` → `2x-4=0` → `x=2`), including candidate roots and
rejected extraneous candidates — and `result` is a `List` of the same
roots `solve()` returns. Systems of equations are not supported yet.

For `'D'`, steps are whole-expression states in traversal order: each
textbook rule (sum, product, quotient, power, chain, …) first appears
with its unresolved sub-derivatives as inert `D(…)` terms, which
resolve step by step. The variable is inferred when unambiguous, or
passed via `options.variable`; `result` matches evaluating
`D(expr, variable)`.

Each step carries the expression state after the step, a stable machine
`id` (the key for localization and custom copy) and a default English
`description`. The `initial` property is the canonical form of this
expression — canonicalization happens before the first step is recorded
and is not traced.

By default the step chain is curated: internal bookkeeping steps are
filtered out. Pass `verbosity: 'all'` to get the raw chain (for
debugging and rule authoring).

####### operation?

[`ExplainOperation`](#explainoperation)

####### options?

`ExplainOptions`

</MemberCard>

<MemberCard>

##### Expression.toSignedFunction() {#tosignedfunction}

```ts
toSignedFunction(): Expression | undefined
```

For a relation expression (`Equal`, `Less`, `Greater`, `LessEqual`,
`GreaterEqual`, `NotEqual`), return the "signed function" form
useful for implicit-surface rendering and region classification:

- `Equal(a, b)` → `a - b` (zero on the surface)
- `Less(a, b)` / `LessEqual(a, b)` → `a - b` (negative when relation holds)
- `Greater(a, b)` / `GreaterEqual(a, b)` → `b - a` (negative when relation holds)
- `NotEqual(a, b)` → `a - b` (caller checks ≠ 0)

For non-relation expressions, returns `undefined`.

Strictness (strict vs non-strict inequality) and direction (less vs
greater) are encoded in the original `expr.operator`, not in the
returned expression. Callers handling 3D implicit rendering use
`expr.operator` for the boundary policy and the signed function for
the interior/exterior classification.

Notes:
- CE canonical form normalizes `GreaterEqual(a, b)` to `LessEqual(b, a)`
  (and similarly `Greater` to `Less`). Callers using `toSignedFunction()`
  on canonicalized parsed expressions will see `LessEqual`/`Less` rather
  than `GreaterEqual`/`Greater`. The signed-function semantics are
  preserved through the normalization. The `GreaterEqual`/`Greater`
  branches handle non-canonical expressions constructed via
  `ce.expr(['GreaterEqual', ...])`.
- For chained relations with more than two operands (e.g.
  `Less(a, b, c)` from `a < b < c`), only the first pair is used.
  The result is the signed function for the first sub-relation only;
  3D implicit rendering rarely uses chained relations, but if it
  does, callers should decompose first.

</MemberCard>

<MemberCard>

##### Expression.getInterval() {#getinterval}

```ts
getInterval(symbol): IntervalBounds | undefined
```

For an expression representing a domain restriction (a restriction whose
condition is a comparison or `And` of comparisons over `symbol`, or
a bare comparison expression), return the lower/upper bounds for
`symbol`. Returns `undefined` if no bounds can be extracted.

Supported shapes:
- Bare comparisons: `a < x`, `x < b`, etc.
- Chained comparisons: `a < x < b` (parsed as `Less(a, x, b)`)
- `And(c1, c2, ...)` where each `ci` is a supported shape
- `If(cond, e)` — operates on `cond`
- `Multiply(f, If(...), ...)` — the Desmos parse shape for
  `f(x)\{a < x < b\}`; bounds from each restriction factor are merged

`lowerStrict`/`upperStrict` are `true` for strict (`<`, `>`) bounds
and `false` for non-strict (`≤`, `≥`).

Returns `undefined` for unsupported shapes (e.g. equations, non-linear
constraints, comparisons over multiple symbols, disjunctions).

####### symbol

`string`

</MemberCard>

<MemberCard>

##### Expression.evaluate() {#evaluate-2}

```ts
evaluate(options?): Expression
```

Return the value of the canonical form of this expression.

A pure expression always returns the same value (provided that it
remains constant / values of sub-expressions or symbols do not change),
and has no side effects.

Evaluating an impure expression may return a varying value, and may have
some side effects such as adjusting symbol assumptions.

To perform approximate calculations, use `expr.N()` instead,
or call with `options.numericApproximation` to `true`.

It is possible that the result of `expr.evaluate()` may be the same as
`expr.simplify()`.

The result is in canonical form.

**Time and recursion limits**: if the evaluation runs inside an enclosing
[`ComputeEngine.withTimeLimit`](#withtimelimit)
span and exceeds its deadline, spends an enclosing
[`ComputeEngine.withStepBudget`](#withstepbudget)
budget, or exceeds the recursion limit, a `CancellationError` is thrown
(its `cause` is `'timeout'`, `'step-budget'` or
`'recursion-depth-exceeded'`). Catch it to distinguish
an interrupted evaluation from a symbolic (inert) result.

####### options?

`Partial`\<`EvaluateOptions`\>

</MemberCard>

<MemberCard>

##### Expression.evaluateAsync() {#evaluateasync-1}

```ts
evaluateAsync(options?): Promise<Expression>
```

Asynchronous version of `evaluate()`.

The `options` argument can include a `signal` property, which is an
`AbortSignal` object. If the signal is aborted, a `CancellationError` is thrown.

A call made inside a
[`ComputeEngine.withTimeLimit`](#withtimelimit)
(or `withStepBudget`) span keeps the span's limit for the whole
evaluation, the parts that run after an `await` included: the limit is
read when `evaluateAsync()` is called, not when the span closes. A
limit that expires is reported as it is by `evaluate()`.
A span around a nested `evaluateAsync(options)` call (from an
asynchronous handler, with the options it received) applies to that
call until it ends, when it ends sooner than the limit of the
evaluation or adds a step budget; the other parts of the evaluation
keep their own limit. Nested limits combine: the earlier time limit
applies, and a step counts against every step budget in force.

####### options?

`Partial`\<`EvaluateOptions`\>

</MemberCard>

<MemberCard>

##### Expression.N() {#n-1}

```ts
N(): Expression
```

Return a numeric approximation of the canonical form of this expression.

Any necessary calculations, including on decimal numbers (non-integers),
are performed.

The calculations are performed according to the
`precision` property of the `ComputeEngine`.

To only perform exact calculations, use `this.evaluate()` instead.

If the function is not numeric, the result of `this.N()` is the same as
`this.evaluate()`.

The result is in canonical form.

Note on typing (SYMBOLIC P2-24, by design): `N()` produces a float
literal, so its `type` can widen relative to the exact input's — e.g.
`1/3` has type `rational` while `(1/3).N()` has type
`real`. The result type reflects the representation produced,
not the mathematical value's tightest type.

</MemberCard>

<MemberCard>

##### Expression.solve() {#solve}

```ts
solve(vars?): 
  | readonly Expression[]
  | Record<string, Expression>
  | Record<string, Expression>[]
  | null
```

If this is an equation, solve the equation for the variables in vars.
Otherwise, solve the equation `this = 0` for the variables in vars.

For univariate equations, returns an array of solutions (roots). For a
trigonometric equation, the array holds the principal roots: one root of
each family of roots in one period, with no free parameter
(`sin(x) = 1/2` gives `[π/6, 5π/6]`). This is different from the `Solve`
operator, which gives the families themselves with a fresh integer
parameter `t` (`[π/6 + 2πt, 5π/6 + 2πt]`), so that its list holds every
root. Returns `null` when the solver
cannot solve the equation, and also when it can find only a part of the
roots: when the unknown is in a function that the solver cannot invert
and that is not periodic (`(x - 1)·BesselJ(0, x) = 0`), or in a factor of
a product that gives no root and is not shown to have none
(`(x - 2)(x + e^x) = 0`).
For systems of linear equations (List of Equal expressions), returns
an object mapping variable names to their values.
For non-linear polynomial systems (like xy=6, x+y=5), returns an array
of solution objects (multiple solutions possible).

```javascript
// Univariate equation
const expr = ce.parse("x^2 + 2*x + 1 = 0");
console.log(expr.solve("x")); // Returns array of roots

// System of linear equations
const system = ce.parse("\\begin{cases}x+y=70\\\\2x-4y=80\\end{cases}");
console.log(system.solve(["x", "y"])); // Returns { x: 60, y: 10 }

// Non-linear polynomial system (product + sum)
const nonlinear = ce.parse("\\begin{cases}xy=6\\\\x+y=5\\end{cases}");
console.log(nonlinear.solve(["x", "y"])); // Returns [{ x: 2, y: 3 }, { x: 3, y: 2 }]
```

####### vars?

  \| `string`
  \| `Iterable`\<`string`, `any`, `any`\>
  \| [`Expression`](#expression-5)
  \| `Iterable`\<[`Expression`](#expression-5), `any`, `any`\>

</MemberCard>

<MemberCard>

##### Expression.value {#value-6}

```ts
get value(): Expression | undefined
set value(value: 
  | number[]
  | ExpressionInput
  | OnlyFirst<{
  re: number;
  im: number;
 }, {
  re: number;
  im: number;
 } & {
  num: number;
  denom: number;
 } & Expression>
  | OnlyFirst<{
  num: number;
  denom: number;
 }, {
  re: number;
  im: number;
 } & {
  num: number;
  denom: number;
 } & Expression>
  | OnlyFirst<Expression, {
  re: number;
  im: number;
 } & {
  num: number;
  denom: number;
 } & Expression>
  | undefined): void
```

If this expression is a number literal, a string literal or a function
 literal, return the expression.

If the expression is a symbol, return the value of the symbol.

Otherwise, the expression is a symbolic expression, including an unknown
symbol, i.e. a symbol with no value, return `undefined`.

If the expression is a symbol, set the value of the symbol.

Will throw a runtime error if either not a symbol, or a symbol with the
`constant` flag set to `true`.

Setting the value of a symbol results in the forgetting of all assumptions
about it in the current scope.

</MemberCard>

<MemberCard>

##### Expression.isCollection {#iscollection-1}

```ts
isCollection: boolean;
```

Is `true` if the expression is a collection.

When `isCollection` is `true`, the expression:

- has an `each()` method that returns a generator over the elements
  of the collection.
- has a `size` property that returns the number of elements in the
  collection.
- has a `contains(other)` method that returns `true` if the `other`
  expression is in the collection.

### `isCollection` is a CAPABILITY, `type.matches('collection<any>')` is a SHAPE

This is the single most common source of collection-handling bugs in the
engine, so it is worth stating precisely. The two predicates answer
different questions and neither implies the other:

- `isCollection` — "can I enumerate this **now**?" It is `false` for a
  symbol declared `list<number>`/`vector<2>` that has not been assigned
  yet, and for an application whose head returns a collection (`L(1)`
  under `L: (number) -> vector<2>`): both are collection-shaped, but
  there is nothing to walk. To ask what shape an expression promises
  before evaluation (`L(1)` promises an indexed collection of 2
  elements), read `staticShape`.
- `type.matches('collection<any>')` — "is this operand
  collection-**shaped**?" It is `true` for those valueless cases, and
  `false` for a materialized collection whose type is top
  (`unknown`/`any`), which `isCollection` reports `true`.

A shape test should spell the `<any>` FAMILY TOP rather than the bare
name. Since 0.160.0 the bare `collection` also matches `list<any>`,
`list<nothing>` and `list<integer|missing>`, but the explicit top does
not depend on how the bare name is read.
(`COLLECTION_SHAPE_TYPE` and friends in `common/type/primitive.ts` are
the same tops as `Type` constants, for `isSubtype` call sites.)

Pick by the question you are actually asking:

- About to call `each()`, `contains()`, `at()`, or read `count` — that is
  a capability question. Use `isCollection`.
- Deciding whether an operand takes the SCALAR path or the
  collection/broadcast path — that is a shape question. Test
  `isCollection || type.matches('collection<any>')`, or the operand class
  alone with `isValuelessCollectionTyped()` (`collection-utils.ts`).

Getting this wrong has a characteristic signature: the operator takes its
scalar path for an operand that is not a scalar and commits an answer that
the SAME expression contradicts once the symbol is assigned. A 2026-08-15
audit of all 95 `isCollection` sites found seven operator families doing
exactly that — `Sum(L)` answering `L`, `Union(L, Set(1))` collapsing `L`
into a single element, `SetMinus` INVERTING a membership answer,
`Mean(L)` committing `NaN`, `Which` throwing on a `list<boolean>`
condition. Pinned in
`test/compute-engine/valueless-collection-typed-operand.test.ts`, which is
the place to add a case if you touch this.

A third predicate covers a distinct case: `isPossiblyCollectionTyped()`
(`collection-utils.ts`) is for an operand that MIGHT become a collection
at runtime — a top-typed application, or a `broadcastable<T>` — where the
honest answer is that the shape is not statically visible at all.

One more operand class answers a confident `false` to BOTH `isCollection`
and `type.matches('collection<any>')` while still being able to hold a
collection: a union of a scalar branch and a collection branch — a
valueless `u: number | list<number>`, and the `2u` lifted over it, since a
broadcast over such an operand carries the union through rather than
claiming a definite list. The scalar branch defeats the match, so a gate
that must decline for a MAYBE-collection has to ask one of the two
union predicates in `collection-utils.ts` as well:
`unionMayHoldACollection()` for an ENUMERATION gate (a big op folding its
body — tuple, string and fixed-shape branches enumerate too), or
`scalarOrCollectionUnionBranches()` for a BROADCAST gate.

</MemberCard>

<MemberCard>

##### Expression.staticShape {#staticshape-1}

```ts
readonly staticShape: StaticShape | undefined;
```

The collection shape that this expression promises, or `undefined` when
it promises no collection.

It does not evaluate an application or a symbol. For a collection value
it reads the collection facets, and the `count` of a lazy view over an
eager source (`Join(f(1), [4])`, a `Filter`) evaluates that source: it
calls `f`, or runs the filter's function once per element.

`staticShape` answers the SHAPE question: "what does this expression
promise to be?". `isCollection` answers the CAPABILITY question: "is a
collection value present that I can walk now?". The two differ for an
expression that has no value yet:

```js
ce.assign('f', ce.parse('n \\mapsto [n, n+1, n+2, n/2]'));
const e = ce.box(['f', 3]);
e.isCollection;  // false: nothing to walk before evaluation
e.count;         // undefined
e.staticShape;   // { indexed: true, count: 4, elementType: 'rational' }
```

The answer comes from:

- the collection facets, when `isCollection` is `true` (a list, a
  string, a dictionary, a symbol that holds a collection);
- the declared type of a symbol with no collection value
  (`L: vector<2>` gives a count of 2). A type that the engine inferred
  from the uses of an undeclared name is not a promise;
- the static type of an application whose head is bound: a library
  operator, a function literal assigned to a name, or a declared
  signature. A call of an undeclared name (`foo([1, 2])`) promises
  nothing, although its type lifts over the collection argument. A
  broadcast (`x + 1`) promises a collection only when one of its
  operands promises one. A `missing` or `nothing` arm of the type is an
  absence of the whole value and is set aside; a type with a scalar arm
  or a string type promises nothing;
- the arms of a selection (`If(c, a, b)`, `Which`), when every arm
  promises a collection and no arm is a point or a string.

`each()` and `at()` give the elements of the VALUE. When the value
does not have the declared type, `each()` can give another number of
elements than `staticShape.count`; the host must supply values of the
declared types.

</MemberCard>

<MemberCard>

##### Expression.array {#array-3}

```ts
readonly array: readonly number[] | undefined;
```

The elements of a `List` as plain machine numbers, or `undefined`.

Defined for a `List` whose every element is a machine number: an
integer, a finite double, an infinity or `NaN`. A list built by
`ce.list()` answers its own frozen array without boxing an element; an
ordinary list answers a frozen array computed once from its elements.
An element that is not a machine number — an exact rational such as
`1/3`, a radical, a bignum with more digits than a double holds, a
complex number, a symbol, a nested list — makes the answer `undefined`:
the value is never approximated. Evaluate with `.N()` first to get the
floats of an exact list.

The array is frozen. It may be passed as is into a compiled function's
argument bag.

:category: Collections

</MemberCard>

<MemberCard>

##### Expression.isMachineNumeric {#ismachinenumeric}

```ts
readonly isMachineNumeric: boolean;
```

Does `array` reproduce this expression, exactness included?

For a `List`: `true` when `array` is defined and `ce.list(expr.array)`
is this list element for element, as the interpreter computes with it.
A list built by `ce.list()` answers `true` in constant time. An
ordinary list answers `true` when every element is a float with a
fraction part or an exact integer a double holds. It answers `false`
when some element is a float with an integer value, such as `2.0`:
`ce.list()` boxes the double `2` as the exact integer `2`. It answers
`false` too when some element is an exact non-integer such as the
rational `1/2`: `array` admits it, since a
double holds `0.5` with no rounding, but re-boxing `0.5` gives a float,
which computes as one (`0.5 / 3` is `0.1666…` where `1/2 ÷ 3` is
`1/6`). A consumer that must keep exact values exact takes `array` only
when this is `true`.

For a number: `true` when the number is a float with a fraction part
or past the safe integers, an exact integer a double holds, `NaN` or an
infinity; `false` for a float with a safe-integer value (`2.0`), an
exact non-integer, a radical or a complex number.

`false` for every other expression.

:category: Collections

</MemberCard>

<MemberCard>

##### Expression.isIndexedCollection {#isindexedcollection}

```ts
isIndexedCollection: boolean;
```

Is `true` if this is an indexed collection, such as a list, a vector,
a matrix, a tuple, etc...

The elements of an indexed collection can be accessed by a one-based
index.

When `isIndexedCollection` is `true`, the expression:
- has an `each()`, `size()` and `contains(rhs)` methods
   as for a collection.
- has an `at(index: number)` method that returns the element at the
   specified index.
- has an `indexWhere(predicate: (element: Expression) => boolean)`
   method that returns the index of the first element that matches the
   predicate.

</MemberCard>

<MemberCard>

##### Expression.isLazyCollection {#islazycollection}

```ts
isLazyCollection: boolean;
```

False if not a collection, or if the elements of the collection
are not computed lazily.

The elements of a lazy collection are computed on demand, when
iterating over the collection using `each()`.

Use `ListFrom` and related functions to create eager collections from
lazy collections.

</MemberCard>

<MemberCard>

##### Expression.each() {#each}

```ts
each(): Generator<Expression>
```

If this is a collection, return an iterator over the elements of the
collection.

```js
const expr = ce.parse('[1, 2, 3, 4]');
for (const e of expr.each()) {
 console.log(e);
}
```

`each()` gives the elements of the value, and `staticShape.count` gives
the number of elements that the expression promises before evaluation.
The two can differ when the value does not have the declared type: a
call of a function declared `(integer) -> vector<3>` whose body gives
two elements has a `staticShape.count` of 3, but its value gives two
elements. The host must supply values of the declared types. Read
`staticShape` for the promised shape and `each()` for the elements.

</MemberCard>

<MemberCard>

##### Expression.contains() {#contains-1}

```ts
contains(rhs): boolean | undefined
```

If this is a collection, return true if the `rhs` expression is in the
collection.

Return `undefined` if the membership cannot be determined without
iterating over the collection.

####### rhs

[`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.subsetOf() {#subsetof-1}

```ts
subsetOf(other, strict): boolean | undefined
```

Check if this collection is a subset of another collection, i.e.
`this` ⊆ `other`.

Returns `undefined` when the relation cannot be determined — including
when this expression is not (yet) a collection.

####### other

[`Expression`](#expression-5)

The other collection to check against.

####### strict

`boolean`

If true, the subset relation is strict (i.e., proper subset).

</MemberCard>

<MemberCard>

##### Expression.count {#count-2}

If this is a collection, return the number of elements in the collection.

Only top-level elements are counted: for a nested collection (e.g. a
matrix represented as a list of lists), this is the number of immediate
elements (the rows), not the total number of scalar entries. For example
the count of `[[2, 3, 4], [6, 7, 9]]` is 2, not 6. This is consistent
with `each()` and `at()`, which iterate over and index the same elements.

If the collection is infinite, return `Infinity`.

If the number of elements cannot be determined, return `undefined`, for
example, if the collection is lazy and not finite and the size cannot
be determined without iterating over the collection.

For the length that an expression with no value yet promises (a call of
a function that returns a list), read `staticShape.count`.

The count is a `bigint` only when it is finite and is not a safe integer
(larger than `Number.MAX_SAFE_INTEGER`), for example the count of
`QuotientRing(Integers, 2^61 - 1)`. A count that is a safe integer is
always a `number`, and an infinite count is `Infinity`. Do not mix the
count with a `number` in arithmetic before you check its type:
JavaScript throws a `TypeError` for `count + 1` when `count` is a
`bigint`. A comparison (`count > 10`) is valid for both types.

</MemberCard>

<MemberCard>

##### Expression.isFiniteCollection {#isfinitecollection}

```ts
isFiniteCollection: boolean | undefined;
```

If this is a finite collection, return true.

</MemberCard>

<MemberCard>

##### Expression.isEmptyCollection {#isemptycollection}

```ts
isEmptyCollection: boolean | undefined;
```

If this is an empty collection, return true.

An empty collection has a size of 0.

</MemberCard>

<MemberCard>

##### Expression.isEnumerableCollection {#isenumerablecollection}

```ts
isEnumerableCollection: boolean | undefined;
```

Whether `each()` yields this collection's actual elements.

This is the cheap predicate that separates the two reasons `each()` can
produce nothing:

- `true`: the elements are enumerable, so a walk that yields nothing
  means the collection is **empty**.
- `false`: the elements cannot be produced in the current state, so a
  walk that yields nothing means **nothing at all**. For example
  `Range(a, b)` with free variables, `Repeat(3, n)` with a symbolic
  count, or a wrapper over such a source (`Take(Range(a, b), 2)`).
- `undefined`: undecidable without evaluating — an *eager* collection
  operator (`Characters(s)`, `UnicodeScalars(s)`) has no collection
  handlers until it is evaluated, yet `each()` walks it through the
  materialize-then-iterate path.

An arithmetic **broadcast** (`x + [1, 2]`, `Sin(1..99)` — a
`broadcastable` operator whose collection-ness is a lift over its
operands) answers from its participants: `true` when they agree on a
length, evaluation is draw-free, and every collection-typed participant
is itself enumerable; `false` when a participant is definitively
unwalkable (a valueless symbol, an application of an UNBOUND head —
`x + Total([1, 2])` with `Total` undeclared binds vacuously and can
never produce elements); `undefined` when the lengths disagree or an
impure participant (`RandomShuffle(xs) + 1`) makes per-index reads
unable to promise draw coherence — there `each()` still walks, but
`at()` declines. Impurity confined to a *scalar* (lifted) operand does
not demote the answer: `[1, 2] + RandomInteger(1, 10)` is `true` — its
evaluation distributes structurally without consuming randomness, and
both `each()` and `at()` serve the unevaluated elements.

Independent of `count`: a collection can know its size and still not be
enumerable (`Linspace(a, 1, 3)` has a count of 3 and no computable
elements), and an enumerable collection can have an unknown size.

Answered structurally, without evaluating: O(1) for a leaf, O(depth) for
a chain of wrappers.

</MemberCard>

<MemberCard>

##### Expression.at() {#at-2}

```ts
at(index): Expression | undefined
```

If this is an indexed collection, return the element at the specified
 index. The first element is at index 1.

If the index is negative, return the element at index `size() + index + 1`.

The last element is at index -1.

####### index

`number`

</MemberCard>

<MemberCard>

##### Expression.get() {#get}

```ts
get(key): Expression | undefined
```

If this is a keyed collection (map, record, tuple), return the value of
the corresponding key.

If `key` is a `Expression`, it should be a string.

####### key

`string` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.indexWhere() {#indexwhere-1}

```ts
indexWhere(predicate): number | undefined
```

If this is an indexed collection, return the index of the first element
that matches the predicate.

####### predicate

(`element`) => `boolean`

</MemberCard>

#### Primitive Methods

<MemberCard>

##### Expression.valueOf() {#valueof-2}

```ts
valueOf(): string | number | boolean | number[] | number[][] | number[][][]
```

Return a JavaScript primitive value for the expression, based on
`Object.valueOf()`.

This method is intended to make it easier to work with JavaScript
primitives, for example when mixing JavaScript computations with
symbolic computations from the Compute Engine.

If the expression is a **machine number**, a **bignum**, or a **rational**
that can be converted to a machine number, return a JavaScript `number`.
This conversion may result in a loss of precision.

If the expression is the **symbol `"True"`** or the **symbol `"False"`**,
return `true` or `false`, respectively.

If the expression is a **symbol with a numeric value**, return the numeric
value of the symbol.

If the expression is a **string literal**, return the string value.

If the expression is a **tensor** (list of number or multidimensional
array or matrix), return an array of numbers, or an array of
arrays of numbers, or an array of arrays of arrays of numbers.

If the expression is a function expression return a string representation
of the expression.

</MemberCard>

<MemberCard>

##### Expression.\[toPrimitive\]() {#toprimitive-2}

```ts
toPrimitive: string | number | null
```

Similar to`expr.valueOf()` but includes a hint.

####### hint

`"string"` \| `"number"` \| `"default"`

</MemberCard>

<MemberCard>

##### Expression.toString() {#tostring-2}

```ts
toString(): string
```

Return an ASCIIMath representation of the expression. This string is
suitable to be output to the console for debugging, for example.

Based on `Object.toString()`.

To get a LaTeX representation of the expression, use `expr.latex`.

Note that lazy collections are eagerly evaluated.

Used when coercing a `Expression` to a `String`.

For arbitrary-precision numbers (`BigNumericValue`), the output is
rounded to the precision of the engine (`ce.precision`) in significant
digits. Digits beyond the working precision are noise from
precision-bounded operations (division, transcendentals) and are not
displayed. Machine-precision numbers use
their native `Number.toString()`.

</MemberCard>

<MemberCard>

##### Expression.toJSON() {#tojson-4}

```ts
toJSON(): MathJsonExpression
```

Used by `JSON.stringify()` to serialize this object to JSON.

Method version of `expr.json`.

Based on `Object.toJSON()`.

Note that lazy collections are *not* eagerly evaluated.

The output preserves the full raw `BigDecimal` value with no rounding,
ensuring lossless round-tripping via `ce.expr(expr.json)`. Digits beyond
`ce.precision` may be present but are not guaranteed to be accurate.
Use `toMathJson({ digits: 'auto' })` for precision-rounded
MathJSON output.

</MemberCard>

<MemberCard>

##### Expression.is() {#is-1}

```ts
is(other, tolerance?): boolean
```

Smart equality check: structural first, then numeric evaluation fallback.
Symmetric: `a.is(b)` always equals `b.is(a)`.

First tries an exact structural check (same as `isSame()`). If that fails
and the expression is constant (no free variables), evaluates numerically
and compares within `engine.tolerance`.

For literal numbers compared to primitives (`number`, `bigint`), behaves
identically to `isSame()` — no tolerance is applied. Tolerance only
applies to expressions that require evaluation (e.g., `\\sin(\\pi)`).

```typescript
ce.parse('\\cos(\\frac{\\pi}{2})').is(0)  // true — evaluates, within tolerance
ce.number(1e-17).is(0)                     // false — literal, no tolerance
ce.parse('x + 1').is(1)                    // false — has free variables
ce.parse('\\pi').is(3.14, 0.01)            // true — within custom tolerance
```

After the structural check, attempts to expand both sides (distributing
products, applying the multinomial theorem, etc.) and re-checks
structural equality. This catches equivalences like `(x+1)^2` vs
`x^2+2x+1` even when the expression has free variables.

When one side is a value of a value kind (a value made by a head
declared with an `arithmetic` field), the result is the result of
`Equal` for the two sides when the kind type declares `compare` (the
`compare` hook orders the two values within the tolerance: `tolerance`,
else `engine.tolerance`, also for two exact values), and of `isSame()`
otherwise.

####### other

`string` \| `number` \| `bigint` \| `boolean` \| [`Expression`](#expression-5)

####### tolerance?

`number`

If provided, overrides `engine.tolerance` for the
numeric comparison. Has no effect when the comparison is structural
(i.e., when `isSame()` succeeds or the expression has free variables).
When one side is a value of a value kind, it is given to the `compare`
hook of the kind (`ArithmeticContext.tolerance`).

</MemberCard>

#### Relational Operator

<MemberCard>

##### Expression.isSame() {#issame}

```ts
isSame(rhs): boolean
```

Fast exact structural/symbolic equality check.

Returns `true` if the expression is structurally identical to `rhs`.
The value of a symbol is never followed: if `one` is assigned `1`,
`ce.symbol('one').isSame(1)` is `false`.

Two symbols, or two calls, with the same name are the same only when
they denote the same binding. A call of the library `Sqrt`, boxed before
a user function `Sqrt` is declared in a scope, and a call `Sqrt(y)`
boxed in that scope are not the same: they are calls of two different
functions. Two calls of the library function are the same, also when
they come from two engines. A raw call (boxed with `form: 'raw'`, or
held by `Hold`) has no binding: two raw calls are compared by their
names, and a raw call is not the same as a canonical call.

The elements of a set literal are not ordered, so two sets with the same
elements in a different order are the same:
`ce.box(['Set', 2, 1]).isSame(ce.box(['Set', 1, 2]))` is `true`. A
set-builder (`Set(body, Element(k, S))`) compares its two operands by
position.

A finite `Range` whose bounds and step are integer literals and that has
at most 10,000 elements is the same as the `List` of its integers, and
has the same `hash`: `ce.box(['Range', 1, 3]).isSame(ce.box(['List', 1,
2, 3]))` is `true`. A larger range is compared by its operands only.
The range and the list are the same only when both are calls of the
library functions, or both are raw calls: a raw `Range(1, 3)` is not the
same as a canonical `[1, 2, 3]`, and a call of a user function named
`Range` is not the same as a list.

A character and a one-cluster string with the same content are the same,
although their types are different: `ce.string('a')` is the same as
`ce.character('a')`.

Accepts JavaScript primitives: `number`, `bigint`, `boolean`, `string`.

Does **not** evaluate expressions — purely structural.

`ce.parse('1+x', {form: 'raw'}).isSame(ce.parse('x+1', {form: 'raw'}))` is `false`.

See `expr.is()` for a smart check with numeric evaluation fallback,
`expr.isEqual()` for value equality, and `expr.isIdenticallyEqual()` to
prove an identity in the free variables.

:::info[Note]
Applicable to canonical and non-canonical expressions.
:::

####### rhs

`string` \| `number` \| `bigint` \| `boolean` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.isLess() {#isless}

```ts
isLess(other): boolean | undefined
```

The value of both expressions are compared.

If the expressions cannot be compared, return `undefined`

####### other

`number` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.isLessEqual() {#islessequal}

```ts
isLessEqual(other): boolean | undefined
```

The value of both expressions are compared.

If the expressions cannot be compared, return `undefined`

####### other

`number` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.isGreater() {#isgreater}

```ts
isGreater(other): boolean | undefined
```

The value of both expressions are compared.

If the expressions cannot be compared, return `undefined`

####### other

`number` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.isGreaterEqual() {#isgreaterequal}

```ts
isGreaterEqual(other): boolean | undefined
```

The value of both expressions are compared.

If the expressions cannot be compared, return `undefined`

####### other

`number` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.isEqual() {#isequal}

```ts
isEqual(other): boolean | undefined
```

Mathematical equality (strong equality), that is the value
of this expression and the value of `other` are numerically equal.

An expression without free variables is evaluated numerically, and the
two values are compared. Numbers whose difference is less than
`engine.tolerance` are considered equal. This tolerance is set when the
`engine.precision` is changed to be such that the last two digits are
ignored.

Evaluating the expressions may be expensive. Other options to consider
to compare two expressions include:
- `expr.isSame(other)` for a fast exact structural comparison (no evaluation)
- `expr.is(other)` for a smart check that tries structural first, then
  numeric evaluation fallback for constant expressions
- `expr.isIdenticallyEqual(other)` to prove an identity in the free
  variables, such as `(x+1)^2` vs `x^2+2x+1`

**Examples**

```js
let expr = ce.parse('2 + 2');
console.log(expr.isEqual(4)); // true
console.log(expr.isSame(4)); // false (structural only)
console.log(expr.is(4)); // true (evaluates, within tolerance)

expr = ce.parse('4');
console.log(expr.isEqual(4)); // true
console.log(expr.isSame(4)); // true
console.log(expr.is(4)); // true

```

**Free variables — "truth under constraints" semantics.** When either
expression has free variables, equality means "could these be equal
under the current (and possible) constraints?". The result is `true`
when the two canonical forms are structurally the same (`x+1` vs `1+x`),
and a fact in the assumptions database (`ce.assume(...)`) can decide it
either way: after `ce.assume(ce.parse('x = 4'))`, `x+1` vs `5` is
`true` and `x` vs `3` is `false`. Anything else is `undefined`, never a
definitive `false` — including `x` vs `2`, which an assumption could
make true.

No identity proof is attempted: `(x+1)^2` vs `x^2+2x+1`, and even
`x+x` vs `2x`, are `undefined`. Use `expr.isIdenticallyEqual()` to prove
that two expressions are equal for every value of their free variables.

####### other

`number` \| [`Expression`](#expression-5)

</MemberCard>

<MemberCard>

##### Expression.isIdenticallyEqual() {#isidenticallyequal}

```ts
isIdenticallyEqual(other): boolean | undefined
```

Identity of this expression and `other` in **all** their free variables,
that is `sin(x)^2 + cos(x)^2 ≡ 1`. This is the deepest — and most
expensive — of the three equality tiers:

| Method | Semantics |
| --- | --- |
| `expr.isSame(other)` | **Structural**: syntactic equality of the canonical forms. Always decidable, no evaluation. |
| `expr.isEqual(other)` | **Arithmetic**: the values are equal (within `engine.tolerance`). |
| `expr.isIdenticallyEqual(other)` | **Identity**: the two expressions are equal for every value of their free variables. |

Three-valued: `true` when identity could be established, `false` when the
expressions are provably different, and `undefined` when neither could be
determined. In particular, expressions that merely *disagree* at sampled
points (`x+1` vs `x+2`) are `undefined`, not `false`: an assumption could
still constrain them equal.

Identity is established by stochastic sampling (evaluating both
expressions at random points), falling back to a symbolic
expand-and-simplify proof. A `true` obtained from sampling alone is
therefore a very strong indication, but not a formal proof
([Richardson's theorem](https://en.wikipedia.org/wiki/Richardson%27s_theorem)
makes a complete decision procedure impossible).

This is the API counterpart of the `IdenticallyEqual` operator (`\equiv`
in LaTeX).

####### other

`number` \| [`Expression`](#expression-5)

</MemberCard>

#### Tensor Expression

<MemberCard>

##### Expression.shape {#shape-3}

```ts
readonly shape: number[];
```

The **shape** describes the **axes** of the expression, where each axis
represent a way to index the elements of the expression.

When the expression is a scalar (number), the shape is `[]`.

When the expression is a vector of length `n`, the shape is `[n]`.

When the expression is a `n` by `m` matrix, the shape is `[n, m]`.

</MemberCard>

<MemberCard>

##### Expression.rank {#rank-2}

```ts
readonly rank: number;
```

The **rank** refers to the number of dimensions (or axes) of the
expression.

Return 0 for a scalar, 1 for a vector, 2 for a matrix, > 2 for
a multidimensional matrix.

The rank is equivalent to the length of `expr.shape`

:::info[Note]
There are several definitions of rank in the literature.
For example, the row rank of a matrix is the number of linearly
independent rows. The rank can also refer to the number of non-zero
singular values of a matrix.
:::

</MemberCard>

#### Type Properties

<MemberCard>

##### Expression.type {#type-12}

```ts
get type(): BoxedType
set type(type: 
  | string
  | RecordType
  | AlgebraicType
  | NegationType
  | CollectionType
  | ListType
  | SetType
  | BroadcastableType
  | ObjectType
  | ArrayType
  | DictionaryType
  | TupleType
  | SymbolType
  | ExpressionType
  | NumericType
  | FunctionSignature
  | ValueType
  | TypeVariable
  | TypeReference
  | BoxedType): void
```

The static type of this expression. A symbol reads the declared or
inferred type of its binding. A function call has its result type,
and a function value has its signature.

To test a proposition under the current assumptions, use `ce.verify()`.
For example, a symbol declared `real` keeps that type when an
assumption establishes that it belongs to the integers.

If not valid, return `"error"`.

If the type is not known, return `"unknown"`.

</MemberCard>

<MemberCard>

##### Expression.isNumber {#isnumber}

```ts
readonly isNumber: boolean | undefined;
```

`true` if the value of this expression is a number.

Note that in a fateful twist of cosmic irony, `NaN` ("Not a Number")
**is** a number.

If `isNumber` is `true`, this indicates that evaluating the expression
will return a number.

This does not indicate that the expression is a number literal. To check
if the expression is a number literal, use `expr.isNumberLiteral`.

For example, the expression `["Add", 1, "x"]` is a number if "x" is a
number and `expr.isNumber` is `true`, but `isNumberLiteral` is `false`.

</MemberCard>

<MemberCard>

##### Expression.isInteger {#isinteger}

```ts
readonly isInteger: boolean | undefined;
```

The value of this expression is an element of the set ℤ: ...,-2, -1, 0, 1, 2...

Note that ±∞ and NaN are not integers.

</MemberCard>

<MemberCard>

##### Expression.isRational {#isrational}

```ts
readonly isRational: boolean | undefined;
```

The value of this expression is an element of the set ℚ, p/q with p ∈ ℕ, q ∈ ℤ ⃰  q >= 1

Note that every integer is also a rational.

This is equivalent to `this.type === "rational" || this.type === "integer"`

Note that ±∞ and NaN are not rationals.

</MemberCard>

<MemberCard>

##### Expression.isExtendedReal {#isextendedreal}

```ts
readonly isExtendedReal: boolean | undefined;
```

The value of this expression is on the **extended real line**: a finite
real number, or one of the two signed infinities `+∞` and `-∞`.

The unsigned complex infinity `~∞` is **not** on the extended real line,
and neither is `NaN`; both answer `false`. A number with a non-zero
imaginary part answers `false`.

Use this predicate for a gate that must also hold at `±∞` — sign
reasoning, the `1/±∞ = 0` fold, a claim that a result is a signed
infinity. For a **finite** real, test `this.type.matches("real")`
instead: the bare type name `real` denotes the finite reals.

</MemberCard>

<MemberCard>

##### Expression.isFunction {#isfunction}

```ts
readonly isFunction: boolean | undefined;
```

The value of this expression is a function.

This is equivalent to `this.type.matches("function")`, that is, the
expression evaluates to a function (for example a symbol bound to a
function literal, or a function literal itself).

This is distinct from `isFunctionExpression`, which is a *structural*
property (`true` when the expression is a function application node such
as `["Add", 1, 2]`).

</MemberCard>

#### Value Properties

<MemberCard>

##### Expression.constantValue {#constantvalue}

```ts
readonly constantValue: string | number | boolean | object | undefined;
```

If this expression is constant (see `isConstant`), return its value,
otherwise `undefined`.

</MemberCard>

### DictionaryInterface {#dictionaryinterface}

Interface for dictionary-like structures.
Use `isDictionary()` to check if an expression is a dictionary.

<MemberCard>

##### DictionaryInterface.keys {#keys}

</MemberCard>

<MemberCard>

##### DictionaryInterface.entries {#entries-1}

</MemberCard>

<MemberCard>

##### DictionaryInterface.values {#values}

</MemberCard>

<MemberCard>

##### DictionaryInterface.get() {#get-1}

```ts
get(key): Expression | undefined
```

####### key

`string`

</MemberCard>

<MemberCard>

##### DictionaryInterface.hasKey() {#haskey}

```ts
hasKey(key): boolean
```

True if the dictionary has an entry with the key `key`.

This is the key test. The `has()` method of the expression is the
symbol test: on a dictionary it looks for a symbol in the VALUES and
never matches a key, because a key is a string, not a symbol. For
`{"a" -> u}`, `hasKey("a")` is `true`, `has("a")` is `false` and
`has("u")` is `true`.

####### key

`string`

</MemberCard>

<MemberCard>

### EvaluateModContext {#evaluatemodcontext}

```ts
type EvaluateModContext = {
  engine: ComputeEngine;
  mod: (x) => bigint | undefined;
};
```

The `context` of an `evaluateMod` handler. See
`OperatorDefinition.evaluateMod` (types-definitions.ts).

</MemberCard>

<MemberCard>

### EvaluateModHandler {#evaluatemodhandler}

```ts
type EvaluateModHandler = (ops, modulus, context) => bigint | undefined;
```

The signature of an `evaluateMod` handler.

</MemberCard>

## Serialization

<MemberCard>

### NumberFormat {#numberformat}

```ts
type NumberFormat = {
  positiveInfinity: LatexString;
  negativeInfinity: LatexString;
  notANumber: LatexString;
  imaginaryUnit: LatexString;
  decimalSeparator: LatexString;
  digitGroupSeparator:   | LatexString
     | [LatexString, LatexString];
  digitGroup: "lakh" | number | [number | "lakh", number];
  exponentProduct: LatexString;
  beginExponentMarker: LatexString;
  endExponentMarker: LatexString;
  truncationMarker: LatexString;
  repeatingDecimal: "auto" | "vinculum" | "dots" | "parentheses" | "arc" | "none";
};
```

These options control how numbers are parsed and serialized.

</MemberCard>

<MemberCard>

### NumberSerializationFormat {#numberserializationformat}

```ts
type NumberSerializationFormat = NumberFormat & {
  digits: DisplayDigits;
  notation: "auto" | "engineering" | "scientific" | "adaptiveScientific";
  avoidExponentsInRange:   | undefined
     | null
     | [negativeExponent: number, positiveExponent: number];
};
```

#### NumberSerializationFormat.digits?

```ts
digits?: DisplayDigits;
```

Controls how many digits a number is displayed with. See
[DisplayDigits](#displaydigits).

The LaTeX serializer rounds a float number literal with
`{ fractional: n }` and `{ significant: n }`, and writes an exact number
in full. `"auto"` needs the engine precision, so only `toLatex()` and the
`.latex` getter apply it, when they serialize the expression to MathJSON;
the LaTeX serializer writes every digit of the MathJSON number for
`"auto"` and `"max"`.

</MemberCard>

<MemberCard>

### DisplayDigits {#displaydigits}

```ts
type DisplayDigits = 
  | "auto"
  | "max"
  | {
  significant: number;
 }
  | {
  fractional: number;
};
```

Controls how many digits a number is **displayed** with when serialized.

This is a display/formatting concern only: it does not change the stored
value, nor the precision used for computation.

- `"auto"`: round to the engine's working precision (`ce.precision`). This is
  the default used by the `.latex` getter.
- `"max"`: display all stored digits, with no rounding. This is the default
  used by `.json` / `toMathJson()`.
- `{ significant: n }`: round **inexact** values to `n` significant figures.
  Exact values (integers, rationals, radicals) are displayed in full — this
  is a no-op on them. Truncation only: trailing zeros are not padded
  (`2.0` stays `2`).
- `{ fractional: n }`: display `n` digits after the decimal point, using
  `toFixed` semantics (may pad with trailing zeros, e.g. `2` → `2.00`).

Rounding is orthogonal to notation: it never switches a number to
scientific/exponential notation as a side effect. Fixed-vs-scientific is
controlled by the `notation` / `avoidExponentsInRange` options.

</MemberCard>

<MemberCard>

### JsonSerializationOptions {#jsonserializationoptions}

```ts
type JsonSerializationOptions<T> = KernelJsonSerializationOptions<T>;
```

Options to control serialization to MathJSON when using
`Expression.toMathJson()`.

#### Type Parameters

• T = [`Expression`](#expression-5)

</MemberCard>

## Tensors

<MemberCard>

### DataTypeMap {#datatypemap}

```ts
type DataTypeMap = {
  float64: number;
  float32: number;
  int32: number;
  uint8: number;
  complex128: Complex;
  complex64: Complex;
  bool: boolean;
  expression: Expression;
};
```

Map of `TensorDataType` to JavaScript type.

</MemberCard>

<MemberCard>

### TensorDataType {#tensordatatype}

```ts
type TensorDataType = keyof DataTypeMap;
```

The type of the cells in a tensor.

</MemberCard>

### TensorData {#tensordata}

A record representing the type, shape and data of a tensor.

#### Extended by

- [`Tensor`](#tensor)

<MemberCard>

##### TensorData.dtype {#dtype}

```ts
dtype: DT;
```

</MemberCard>

<MemberCard>

##### TensorData.shape {#shape-1}

```ts
shape: number[];
```

</MemberCard>

<MemberCard>

##### TensorData.rank? {#rank}

```ts
rank?: number;
```

</MemberCard>

<MemberCard>

##### TensorData.data {#data}

```ts
data: DataTypeMap[DT][];
```

</MemberCard>

<MemberCard>

##### TensorData.holdsFloat? {#holdsfloat}

```ts
holdsFloat?: boolean;
```

Is the tensor a float tensor? `true` when an entry of the matrix the
tensor was packed from is a float (a number literal that is not exact,
such as `1.5` or `2.0`), or when the tensor was computed from a float
tensor. Every cell of a float tensor is read back as a float, even when
its value is an integer: the determinant of `[[1.5, 0], [0, 2]]` is the
float `3`, not the exact `3`. Only the numeric dtypes (`float64`,
`complex128`, …) use it: a cell of the `expression` dtype keeps its own
exactness.

</MemberCard>

### TensorField {#tensorfield}

<MemberCard>

##### TensorField.one {#one-2}

```ts
readonly one: T;
```

</MemberCard>

<MemberCard>

##### TensorField.zero {#zero-2}

```ts
readonly zero: T;
```

</MemberCard>

<MemberCard>

##### TensorField.nan {#nan-3}

```ts
readonly nan: T;
```

</MemberCard>

<MemberCard>

##### TensorField.cast() {#cast}

###### cast(x, dtype)

```ts
cast(x, dtype): number | undefined
```

####### x

`T`

####### dtype

`"float64"`

###### cast(x, dtype)

```ts
cast(x, dtype): number | undefined
```

####### x

`T`

####### dtype

`"float32"`

###### cast(x, dtype)

```ts
cast(x, dtype): number | undefined
```

####### x

`T`

####### dtype

`"int32"`

###### cast(x, dtype)

```ts
cast(x, dtype): number | undefined
```

####### x

`T`

####### dtype

`"uint8"`

###### cast(x, dtype)

```ts
cast(x, dtype): Complex | undefined
```

####### x

`T`

####### dtype

`"complex128"`

###### cast(x, dtype)

```ts
cast(x, dtype): Complex | undefined
```

####### x

`T`

####### dtype

`"complex64"`

###### cast(x, dtype)

```ts
cast(x, dtype): boolean | undefined
```

####### x

`T`

####### dtype

`"bool"`

###### cast(x, dtype)

```ts
cast(x, dtype): Expression | undefined
```

####### x

`T`

####### dtype

`"expression"`

###### cast(x, dtype)

```ts
cast(x, dtype): number[] | undefined
```

####### x

`T`[]

####### dtype

`"float64"`

###### cast(x, dtype)

```ts
cast(x, dtype): number[] | undefined
```

####### x

`T`[]

####### dtype

`"float32"`

###### cast(x, dtype)

```ts
cast(x, dtype): number[] | undefined
```

####### x

`T`[]

####### dtype

`"int32"`

###### cast(x, dtype)

```ts
cast(x, dtype): number[] | undefined
```

####### x

`T`[]

####### dtype

`"uint8"`

###### cast(x, dtype)

```ts
cast(x, dtype): Complex[] | undefined
```

####### x

`T`[]

####### dtype

`"complex128"`

###### cast(x, dtype)

```ts
cast(x, dtype): Complex[] | undefined
```

####### x

`T`[]

####### dtype

`"complex64"`

###### cast(x, dtype)

```ts
cast(x, dtype): boolean[] | undefined
```

####### x

`T`[]

####### dtype

`"bool"`

###### cast(x, dtype)

```ts
cast(x, dtype): Expression[] | undefined
```

####### x

`T`[]

####### dtype

`"expression"`

###### cast(x, dtype)

```ts
cast(x, dtype): 
  | number
  | boolean
  | number[]
  | Expression
  | Complex
  | Expression[]
  | Complex[]
  | boolean[]
  | undefined
```

####### x

`T` \| `T`[]

####### dtype

keyof [`DataTypeMap`](#datatypemap)

</MemberCard>

<MemberCard>

##### TensorField.expression() {#expression-3}

```ts
expression(x): Expression
```

####### x

`T`

</MemberCard>

<MemberCard>

##### TensorField.isZero() {#iszero-1}

```ts
isZero(x): boolean
```

####### x

`T`

</MemberCard>

<MemberCard>

##### TensorField.isOne() {#isone-1}

```ts
isOne(x): boolean
```

####### x

`T`

</MemberCard>

<MemberCard>

##### TensorField.equals() {#equals}

```ts
equals(lhs, rhs): boolean
```

####### lhs

`T`

####### rhs

`T`

</MemberCard>

<MemberCard>

##### TensorField.add() {#add-2}

```ts
add(lhs, rhs): T
```

####### lhs

`T`

####### rhs

`T`

</MemberCard>

<MemberCard>

##### TensorField.addn() {#addn}

```ts
addn(...xs): T
```

####### xs

...`T`[]

</MemberCard>

<MemberCard>

##### TensorField.neg() {#neg-1}

```ts
neg(x): T
```

####### x

`T`

</MemberCard>

<MemberCard>

##### TensorField.sub() {#sub-1}

```ts
sub(lhs, rhs): T
```

####### lhs

`T`

####### rhs

`T`

</MemberCard>

<MemberCard>

##### TensorField.mul() {#mul-1}

```ts
mul(lhs, rhs): T
```

####### lhs

`T`

####### rhs

`T`

</MemberCard>

<MemberCard>

##### TensorField.muln() {#muln}

```ts
muln(...xs): T
```

####### xs

...`T`[]

</MemberCard>

<MemberCard>

##### TensorField.div() {#div-1}

```ts
div(lhs, rhs): T
```

####### lhs

`T`

####### rhs

`T`

</MemberCard>

<MemberCard>

##### TensorField.pow() {#pow-1}

```ts
pow(rhs, n): T
```

####### rhs

`T`

####### n

`number`

</MemberCard>

<MemberCard>

##### TensorField.conjugate() {#conjugate}

```ts
conjugate(x): T
```

####### x

`T`

</MemberCard>

### Tensor {#tensor}

#### Extends

- [`TensorData`](#tensordata)\<`DT`\>

<MemberCard>

##### Tensor.dtype {#dtype-1}

```ts
dtype: DT;
```

</MemberCard>

<MemberCard>

##### Tensor.shape {#shape-2}

```ts
shape: number[];
```

</MemberCard>

<MemberCard>

##### Tensor.rank {#rank-1}

```ts
rank: number;
```

</MemberCard>

<MemberCard>

##### Tensor.data {#data-1}

```ts
data: DataTypeMap[DT][];
```

</MemberCard>

<MemberCard>

##### Tensor.field {#field}

```ts
readonly field: TensorField<DataTypeMap[DT]>;
```

</MemberCard>

<MemberCard>

##### Tensor.expression {#expression-4}

```ts
readonly expression: Expression;
```

</MemberCard>

<MemberCard>

##### Tensor.array {#array-2}

```ts
readonly array: NestedArray<DataTypeMap[DT]>;
```

</MemberCard>

<MemberCard>

##### Tensor.isSquare {#issquare}

```ts
readonly isSquare: boolean;
```

</MemberCard>

<MemberCard>

##### Tensor.isSymmetric {#issymmetric}

```ts
readonly isSymmetric: boolean;
```

</MemberCard>

<MemberCard>

##### Tensor.isSkewSymmetric {#isskewsymmetric}

```ts
readonly isSkewSymmetric: boolean;
```

</MemberCard>

<MemberCard>

##### Tensor.isDiagonal {#isdiagonal}

```ts
readonly isDiagonal: boolean;
```

</MemberCard>

<MemberCard>

##### Tensor.isUpperTriangular {#isuppertriangular}

```ts
readonly isUpperTriangular: boolean;
```

</MemberCard>

<MemberCard>

##### Tensor.isLowerTriangular {#islowertriangular}

```ts
readonly isLowerTriangular: boolean;
```

</MemberCard>

<MemberCard>

##### Tensor.isTriangular {#istriangular}

```ts
readonly isTriangular: boolean;
```

</MemberCard>

<MemberCard>

##### Tensor.isIdentity {#isidentity}

```ts
readonly isIdentity: boolean;
```

</MemberCard>

<MemberCard>

##### Tensor.isZero {#iszero-2}

```ts
readonly isZero: boolean;
```

</MemberCard>

<MemberCard>

##### Tensor.at() {#at-1}

```ts
at(...indices): DataTypeMap[DT] | undefined
```

####### indices

...`number`[]

</MemberCard>

<MemberCard>

##### Tensor.diagonal() {#diagonal}

```ts
diagonal(axis1?, axis2?): DataTypeMap[DT][] | undefined
```

####### axis1?

`number`

####### axis2?

`number`

</MemberCard>

<MemberCard>

##### Tensor.trace() {#trace-2}

```ts
trace(axis1?, axis2?): 
  | Tensor<DT>
  | DataTypeMap[DT]
  | undefined
```

####### axis1?

`number`

####### axis2?

`number`

</MemberCard>

<MemberCard>

##### Tensor.reshape() {#reshape}

```ts
reshape(...shape): Tensor<DT>
```

####### shape

...`number`[]

</MemberCard>

<MemberCard>

##### Tensor.slice() {#slice}

```ts
slice(index): Tensor<DT>
```

####### index

`number`

</MemberCard>

<MemberCard>

##### Tensor.flatten() {#flatten}

```ts
flatten(): DataTypeMap[DT][]
```

</MemberCard>

<MemberCard>

##### Tensor.upcast() {#upcast}

```ts
upcast<DT>(dtype): Tensor<DT>
```

• DT extends keyof [`DataTypeMap`](#datatypemap)

####### dtype

`DT`

</MemberCard>

<MemberCard>

##### Tensor.transpose() {#transpose}

```ts
transpose(axis1?, axis2?): Tensor<DT> | undefined
```

####### axis1?

`number`

####### axis2?

`number`

</MemberCard>

<MemberCard>

##### Tensor.conjugateTranspose() {#conjugatetranspose}

```ts
conjugateTranspose(axis1?, axis2?): Tensor<DT> | undefined
```

####### axis1?

`number`

####### axis2?

`number`

</MemberCard>

<MemberCard>

##### Tensor.determinant() {#determinant}

```ts
determinant(): DataTypeMap[DT] | undefined
```

</MemberCard>

<MemberCard>

##### Tensor.inverse() {#inverse}

```ts
inverse(): Tensor<DT> | undefined
```

</MemberCard>

<MemberCard>

##### Tensor.pseudoInverse() {#pseudoinverse}

```ts
pseudoInverse(): Tensor<DT> | undefined
```

</MemberCard>

<MemberCard>

##### Tensor.adjugateMatrix() {#adjugatematrix}

```ts
adjugateMatrix(): Tensor<DT> | undefined
```

</MemberCard>

<MemberCard>

##### Tensor.minor() {#minor}

```ts
minor(axis1, axis2): DataTypeMap[DT] | undefined
```

####### axis1

`number`

####### axis2

`number`

</MemberCard>

<MemberCard>

##### Tensor.map1() {#map1}

```ts
map1(fn, scalar): Tensor<DT>
```

####### fn

(`lhs`, `rhs`) => [`DataTypeMap`](#datatypemap)\[`DT`\]

####### scalar

[`DataTypeMap`](#datatypemap)\[`DT`\]

</MemberCard>

<MemberCard>

##### Tensor.map2() {#map2}

```ts
map2(fn, rhs): Tensor<DT>
```

####### fn

(`lhs`, `rhs`) => [`DataTypeMap`](#datatypemap)\[`DT`\]

####### rhs

[`Tensor`](#tensor)\<`DT`\>

</MemberCard>

<MemberCard>

##### Tensor.add() {#add-3}

```ts
add(other): Tensor<DT>
```

####### other

[`Tensor`](#tensor)\<`DT`\> \| [`DataTypeMap`](#datatypemap)\[`DT`\]

</MemberCard>

<MemberCard>

##### Tensor.subtract() {#subtract}

```ts
subtract(other): Tensor<DT>
```

####### other

[`Tensor`](#tensor)\<`DT`\> \| [`DataTypeMap`](#datatypemap)\[`DT`\]

</MemberCard>

<MemberCard>

##### Tensor.multiply() {#multiply-1}

```ts
multiply(other): Tensor<DT>
```

####### other

[`Tensor`](#tensor)\<`DT`\> \| [`DataTypeMap`](#datatypemap)\[`DT`\]

</MemberCard>

<MemberCard>

##### Tensor.divide() {#divide-1}

```ts
divide(other): Tensor<DT>
```

####### other

[`Tensor`](#tensor)\<`DT`\> \| [`DataTypeMap`](#datatypemap)\[`DT`\]

</MemberCard>

<MemberCard>

##### Tensor.power() {#power-1}

```ts
power(other): Tensor<DT>
```

####### other

[`Tensor`](#tensor)\<`DT`\> \| [`DataTypeMap`](#datatypemap)\[`DT`\]

</MemberCard>

<MemberCard>

##### Tensor.equals() {#equals-1}

```ts
equals(other): boolean
```

####### other

[`Tensor`](#tensor)\<`DT`\>

</MemberCard>

## Type

### BoxedType {#boxedtype}

<MemberCard>

##### new BoxedType()

```ts
new BoxedType(type, typeResolver?): BoxedType
```

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)

####### typeResolver?

[`TypeResolver`](#typeresolver)

</MemberCard>

<MemberCard>

##### BoxedType.unknown {#unknown}

```ts
static unknown: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.number {#number}

```ts
static number: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.signed\_infinity {#signed_infinity}

```ts
static signed_infinity: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.infinity {#infinity}

```ts
static infinity: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.nan {#nan}

```ts
static nan: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.complex {#complex}

```ts
static complex: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.real {#real}

```ts
static real: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.integer {#integer}

```ts
static integer: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.string {#string}

```ts
static string: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.character {#character}

```ts
static character: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.dictionary {#dictionary}

```ts
static dictionary: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.setNumber {#setnumber}

```ts
static setNumber: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.setComplex {#setcomplex}

```ts
static setComplex: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.setImaginary {#setimaginary}

```ts
static setImaginary: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.setReal {#setreal}

```ts
static setReal: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.setRational {#setrational}

```ts
static setRational: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.setInteger {#setinteger}

```ts
static setInteger: BoxedType;
```

</MemberCard>

<MemberCard>

##### BoxedType.type {#type}

```ts
readonly type: Type;
```

</MemberCard>

<MemberCard>

##### BoxedType.isPolymorphic {#ispolymorphic}

```ts
readonly isPolymorphic: boolean;
```

True when this type is a **polytype**: a signature carrying a `where`
clause, or an overload set with at least one such arm.

Computed ONCE, here, at construction: every per-call dispatch check
(argument validation, result typing) reads this boolean and is O(1) — it
must never become a tree walk. Polytypes are legal only as signatures, so
the computation itself is a shallow field test.

</MemberCard>

<MemberCard>

##### BoxedType.facts {#facts}

Lazily shared facts of this type, independent of any expression.

</MemberCard>

<MemberCard>

##### BoxedType.typeResolver {#typeresolver}

The resolver this type was created with, so a DERIVED boxed type (a
projection of this one) can be built without losing the ability to name a
user-declared type.

</MemberCard>

<MemberCard>

##### BoxedType.unionMembers {#unionmembers}

The members of a union type, each boxed, or `[this]` for any other type.

Lets a consumer reason arm-by-arm without reading the raw `Type` AST.
Note that a union may be nested inside a parameter (`list<A | B>`), which
this does not reach — `couldMatch()` handles that case directly and is
usually what an arm walk was reaching for.

</MemberCard>

<MemberCard>

##### BoxedType.effects {#effects}

The **latent** effects on this type's arrow: what fires if a value of this
type is invoked. `undefined` when the type is not callable, or when its
arrow states nothing (the inferred track); `[]` when it states `pure`;
`'any'` for "unknown effects"; otherwise the labels, alphabetically
sorted.

This is how an operator asks "what happens if I call this operand?" —
`op.type.effects`, which resolves through symbol bindings because `.type`
does. It is the *invoking* half of the effects model; the *producing*
half — what evaluating an expression does — is `expr.effects`.

For an overload set (an intersection of signatures) the answer is the
union of the arms': an overload with one effect-bearing arm is not pure.

```ts
ce.type('(real) random -> real').effects;  // ➔ ['random']
ce.type('(real) pure -> real').effects;    // ➔ []
ce.type('(real) -> real').effects;         // ➔ undefined
ce.type('number').effects;                 // ➔ undefined
```

</MemberCard>

<MemberCard>

##### BoxedType.isUnknown {#isunknown}

</MemberCard>

<MemberCard>

##### BoxedType.from() {#from}

```ts
static from(type, resolver?): BoxedType
```

Box an ordinary type, sharing immutable type values within a resolver.

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

####### resolver?

[`TypeResolver`](#typeresolver)

</MemberCard>

<MemberCard>

##### BoxedType.forResult() {#forresult}

###### forResult(type, resolver)

```ts
static forResult(type, resolver?): undefined
```

A type-handler result: widen numeric literal cargo to its stored tier,
retaining intentional ranges and resolver context. Undefined declines.
Normalization is shared only for immutable input types.

####### type

`undefined`

####### resolver?

[`TypeResolver`](#typeresolver)

###### forResult(type, resolver)

```ts
static forResult(type, resolver?): BoxedType
```

A type-handler result: widen numeric literal cargo to its stored tier,
retaining intentional ranges and resolver context. Undefined declines.
Normalization is shared only for immutable input types.

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

####### resolver?

[`TypeResolver`](#typeresolver)

###### forResult(type, resolver)

```ts
static forResult(type, resolver?): BoxedType | undefined
```

A type-handler result: widen numeric literal cargo to its stored tier,
retaining intentional ranges and resolver context. Undefined declines.
Normalization is shared only for immutable input types.

####### type

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)
  \| `undefined`

####### resolver?

[`TypeResolver`](#typeresolver)

</MemberCard>

<MemberCard>

##### BoxedType.widen() {#widen}

```ts
static widen(...types): BoxedType
```

####### types

...readonly ([`Type`](#type-3) \| [`BoxedType`](#boxedtype))[]

</MemberCard>

<MemberCard>

##### BoxedType.narrow() {#narrow}

```ts
static narrow(...types): BoxedType
```

####### types

...readonly ([`Type`](#type-3) \| [`BoxedType`](#boxedtype))[]

</MemberCard>

<MemberCard>

##### BoxedType.matches() {#matches}

```ts
matches(other): boolean
```

True when every value of this type is an `other`.

**A polymorphic PATTERN is a consistent existential** (D12): the pattern's
variables are solved against the subject and the match holds iff a
consistent instantiation exists — so
`ce.type('(number) -> number').matches('(T) -> T where T')` is `true`,
the probe users actually mean. `couldMatch` deliberately answers `false`
on the same row (D6's bound-reading, contravariant `any`); the two
predicates diverge by design.

A polymorphic SUBJECT is the `isSubtype` story: rule 1 against a ground
pattern (instantiate-and-check), rule 3 (α-equivalence) against a
polymorphic one.

####### other

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

</MemberCard>

<MemberCard>

##### BoxedType.is() {#is}

```ts
is(other): boolean
```

####### other

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

</MemberCard>

<MemberCard>

##### BoxedType.isDisjointFrom() {#isdisjointfrom}

```ts
isDisjointFrom(other): boolean
```

True when no value can inhabit both this type and `other`.

Use this — not `!matches()` — to decide whether two types are unrelated.
`matches()` answers "is this a subtype of `other`", so two types that
share values without either containing the other (`integer | string` vs
`integer | boolean`) fail `matches()` in both directions.

Conservative in the safe direction: when disjointness cannot be
established the answer is `false` ("they may overlap"), never a false
claim of disjointness. So `!a.isDisjointFrom(b)` reads as *possible*
overlap, and `unknown` overlaps everything.

Throws if `other` is a string that is not a valid type.

####### other

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

</MemberCard>

<MemberCard>

##### BoxedType.couldMatch() {#couldmatch}

```ts
couldMatch(other, options?): boolean
```

True when *some* value inhabits both this type and `other` — "could a
value of this type be an `other`?".

This is the predicate for classifying a value by shape ("might this be a
point, a point list, a matrix"). Prefer it to `matches()`, which answers
"is EVERY value of this type an `other`" and so reports `false` for a
union whose members include exactly the shape asked about:

```ts
const t = ce.type('tuple<number, number> | list<tuple<number, number>>');
t.matches('list<tuple<number, number>>');    // false
t.couldMatch('list<tuple<number, number>>'); // true
```

Unions are distributed at every depth, so a union nested inside a
parameter is handled too — `list<integer | tuple<number, number>>` could
be a `list<tuple<number, number>>`, witness `[(1,2)]`.

Symmetric, and decisive for the composite shapes it models: a
`tuple<number, number>` could not be a `list<tuple<number, number>>`, and
`list<integer^2>` could not be a `list<string^2>`. Two list types with no
dimensions could always match, whatever their elements, because the empty
list is a value of both: `list<integer>` could be a `list<string>`,
witness `[]`. To ask whether a NON-EMPTY value could be both, pass
`{ nonEmpty: true }`: a non-empty collection of both types has elements
of both element types, so the element types are compared too.

```ts
const t = ce.type('list<number>');
t.couldMatch('list<tuple<number, number>>');                     // true
t.couldMatch('list<tuple<number, number>>', { nonEmpty: true }); // false
t.couldMatch('list<integer>', { nonEmpty: true });               // true
```

Only the outer collection must be non-empty: `[[]]` is a value of both
`list<list<number>>` and `list<list<string>>`. For a type that is not a
collection, the option changes nothing. Shapes it does not model
fall back to assignability in either direction, so the answer is never
narrower than `matches()` — with one deliberate exception: `never` is
uninhabited, so nothing could be a `never`.

`unknown` could be anything. Consumers that treat an inconclusive type as
"no" must check `isUnknown` themselves.

Throws if `other` is a string that is not a valid type.

####### other

  \| `string`
  \| [`RecordType`](#recordtype)
  \| [`AlgebraicType`](#algebraictype)
  \| [`NegationType`](#negationtype)
  \| [`CollectionType`](#collectiontype)
  \| [`ListType`](#listtype)
  \| [`SetType`](#settype)
  \| [`BroadcastableType`](#broadcastabletype)
  \| [`ObjectType`](#objecttype)
  \| [`ArrayType`](#arraytype)
  \| [`DictionaryType`](#dictionarytype)
  \| [`TupleType`](#tupletype)
  \| [`SymbolType`](#symboltype)
  \| [`ExpressionType`](#expressiontype)
  \| [`NumericType`](#numerictype)
  \| [`FunctionSignature`](#functionsignature)
  \| [`ValueType`](#valuetype)
  \| [`TypeVariable`](#typevariable)
  \| [`TypeReference`](#typereference)
  \| [`BoxedType`](#boxedtype)

####### options?

####### nonEmpty?

`boolean`

</MemberCard>

<MemberCard>

##### BoxedType.toString() {#tostring}

```ts
toString(): string
```

</MemberCard>

<MemberCard>

##### BoxedType.toJSON() {#tojson}

```ts
toJSON(): string
```

</MemberCard>

<MemberCard>

##### BoxedType.\[toPrimitive\]() {#toprimitive}

```ts
toPrimitive: string | null
```

####### hint

`string`

</MemberCard>

<MemberCard>

##### BoxedType.valueOf() {#valueof}

```ts
valueOf(): string
```

</MemberCard>



## MathJSON

<MemberCard>

### MathJsonAttributes {#mathjsonattributes}

```ts
type MathJsonAttributes = {
  comment: string;
  documentation: string;
  latex: string;
  wikidata: string;
  wikibase: string;
  openmathSymbol: string;
  openmathCd: string;
  sourceUrl: string;
  sourceContent: string;
  sourceOffsets: [start: number, end: number];
};
```

The following properties can be added to any MathJSON expression
to provide additional information about the expression.

</MemberCard>

<MemberCard>

### MathJsonSymbol {#mathjsonsymbol}

```ts
type MathJsonSymbol = string;
```

</MemberCard>

<MemberCard>

### MathJsonNumberObject {#mathjsonnumberobject}

```ts
type MathJsonNumberObject = {
  num: "NaN" | "-Infinity" | "+Infinity" | string;
 } & MathJsonAttributes;
```

A MathJSON numeric quantity.

The `num` string is made of:
- an optional `-` minus sign
- a string of decimal digits
- an optional fraction part (a `.` decimal marker followed by decimal digits)
- an optional repeating decimal pattern: a string of digits enclosed in
   parentheses
- an optional exponent part (a `e` or `E` exponent marker followed by an
  optional `-` minus sign, followed by a string of digits)

It can also consist of the string `NaN`, `-Infinity` or `+Infinity` to
represent these respective values.

A MathJSON number may contain more digits or an exponent with a greater
range than can be represented in an IEEE 64-bit floating-point.

For example:
- `-12.34`
- `0.234e-56`
- `1.(3)`
- `123456789123456789.123(4567)e999`

</MemberCard>

<MemberCard>

### MathJsonSymbolObject {#mathjsonsymbolobject}

```ts
type MathJsonSymbolObject = {
  sym: MathJsonSymbol;
 } & MathJsonAttributes;
```

</MemberCard>

<MemberCard>

### MathJsonStringObject {#mathjsonstringobject}

```ts
type MathJsonStringObject = {
  str: string;
 } & MathJsonAttributes;
```

</MemberCard>

<MemberCard>

### MathJsonFunctionObject {#mathjsonfunctionobject}

```ts
type MathJsonFunctionObject = {
  fn: [MathJsonSymbol, ...MathJsonExpression[]];
 } & MathJsonAttributes;
```

</MemberCard>

<MemberCard>

### DictionaryValue {#dictionaryvalue}

```ts
type DictionaryValue = 
  | boolean
  | number
  | string
  | ExpressionObject
| ReadonlyArray<DictionaryValue>;
```

</MemberCard>

<MemberCard>

### MathJsonDictionaryObject {#mathjsondictionaryobject}

```ts
type MathJsonDictionaryObject = {
  dict: Record<string, DictionaryValue>;
 } & MathJsonAttributes;
```

</MemberCard>

<MemberCard>

### ExpressionObject {#expressionobject}

```ts
type ExpressionObject = 
  | MathJsonNumberObject
  | MathJsonStringObject
  | MathJsonSymbolObject
  | MathJsonFunctionObject
  | MathJsonDictionaryObject;
```

</MemberCard>

<MemberCard>

### MathJsonExpression {#mathjsonexpression}

```ts
type MathJsonExpression = 
  | ExpressionObject
  | number
  | MathJsonSymbol
  | string
  | readonly [MathJsonSymbol, ...MathJsonExpression[]];
```

A MathJSON expression is a recursive data structure.

The leaf nodes of an expression are numbers, strings and symbols.
The dictionary and function nodes can contain expressions themselves.

</MemberCard>



## Type

<MemberCard>

### PrimitiveType {#primitivetype}

```ts
type PrimitiveType = 
  | NumericPrimitiveType
  | "collection"
  | "indexed_collection"
  | "list"
  | "range"
  | "set"
  | "dictionary"
  | "record"
  | "object"
  | "array"
  | "tuple"
  | "value"
  | "scalar"
  | "function"
  | "symbol"
  | "boolean"
  | "string"
  | "character"
  | "regexp"
  | "color"
  | "residue"
  | "measurement"
  | "quantity"
  | "enclosure"
  | "type"
  | "expression"
  | "unknown"
  | "error"
  | "nothing"
  | "missing"
  | "never"
  | "any";
```

A primitive type is a simple type that represents a concrete value.

- `any`: the top type
   - `expression`
   - `error`: an invalid value, such as `["Error", "missing"]`
   - `nothing`: the type of the `Nothing` symbol, the unit type
   - `missing`: the type of the `Missing` symbol, the unit type of an
      absent-but-positioned value (Julia `missing`, R `NA`)
   - `never`: the bottom type
   - `unknown`: a value whose type is not known

- `expression`:
   - a symbolic expression, such as `["Add", "x", 1]`
   - `<value>`
   - `symbol`: a symbol, such as `x`.
   - `function`: a function literal
     such as `["Function", ["Add", "x", 1], "x"]`.

- `value`
   - `scalar`
     - `<number>`
     - `boolean`: a boolean value: `True` or `False`.
     - `character`: exactly one user-perceived character (grapheme cluster).
   - `collection`
      - `set`: a collection of unique expressions, e.g. `set<string>`.
      - `record`: a collection of specific key-value pairs,
         e.g. `record{x: number, y: boolean}`.
      - `dictionary`: a collection of arbitrary key-value pairs
         e.g. `dictionary<string, number>`.
      - `indexed_collection`: collections whose elements can be accessed
            by a numeric index
         - `list`: a collection of expressions, possibly recursive,
             with optional dimensions, e.g. `[number]`, `[boolean^32]`,
             `[number^(2x3)]`. Used to represent a vector, a matrix or a
             tensor when the type of its elements is a number
          - `tuple`: a fixed-size collection of named or unnamed elements,
             e.g. `tuple<number, boolean>`, `tuple<x: number, y: boolean>`.
          - `string`: a string of characters, i.e. an indexed collection of
             `character`. A sibling of `list<character>`, not a subtype.
   - `array`: a mutable array, e.g. `array<integer<0..255>>`. Not a
      collection.

</MemberCard>

<MemberCard>

### NumericPrimitiveType {#numericprimitivetype}

```ts
type NumericPrimitiveType = 
  | "number"
  | "complex"
  | "imaginary"
  | "real"
  | "rational"
  | "integer"
  | "infinity"
  | "nan";
```

The numeric tree is FINITE BY DEFAULT and DISJOINT: every numeric VALUE is a
finite number, a number of infinite magnitude, or the not-a-number marker,
and no value is two of those — `number = complex ⊔ infinity ⊔ nan` as a
partition of the values. Every bare name below `complex` contains only
finite values. A bare `real` result type is therefore a promise of
finiteness, and the extended real line is spelled
`real | signed_infinity` — `signed_infinity` being the named union of
the two signed-infinity value types (equivalently `real | +oo | -oo`),
so it excludes the unsigned `~∞` that `infinity` would bring in. That
spelling is shared as the frozen `EXTENDED_REAL_TYPE` constant in
`common/type/primitive.ts`; use it rather than rebuilding the union.

The partition is a statement about values, NOT one the SUBTYPE RELATION
closes over. `isSubtype('complex | infinity | nan', 'number')` is true, but
the converse `isSubtype('number', 'complex | infinity | nan')` is FALSE: a
union is a supertype only of types below one of its members, and `number` is
above all three rather than inside any one of them. Deciding the converse
needs covering-union machinery that the type checker does not have. So do
not use a three-way union as a stand-in for `number` in a signature, and do
not read the `⊔` above as a subtyping identity.

- `number`: any numeric value — a finite number, a number of infinite
  magnitude, or the not-a-number marker.
- `complex`: a FINITE complex number = `imaginary` + `real`.
- `imaginary`: a finite complex number with a real part of 0 (pure
  imaginary).
- `real`: a finite real number (imaginary part 0) = `rational` plus the
  finite irrationals.
- `rational`: a finite rational number (includes the integers).
- `integer`: a finite whole number.
- `infinity`: a number of infinite magnitude, of any direction — the signed
  `+∞` and `−∞`, the unsigned complex infinity `~∞`, and mixed directed
  values such as `∞ + i`. Disjoint from `complex`: an infinity is not a
  finite number.
- `nan`: the not-a-number marker. Its only supertype is `number`, so it is
  disjoint from `complex`, `infinity` and every type below them.

The SIGNED pair `+∞`/`−∞` has no one-word name: spell it `+oo | -oo`
(the union of the two value types) where the sign-aware guarantee
matters — the `1/±∞ = 0` folds, the sign-reading gates — and `infinity`
where any infinite value is acceptable. The former one-word name
`non_finite_number` was retired 2026-08-31 (ruling L5 executed): the
name was misleading — `~∞` and `∞ + i` are non-finite numbers, yet
neither was a member.

RETIRED SPELLINGS. The five names that prefixed a tier with `finite_` are
no longer members of this union. Each denoted exactly the same set of values
as one of the bare names above, because every bare name under `number` is
finite: the four per-tier spellings each meant their own tier, and the
widest of them meant `complex` ("any finite number" IS the finite complex
type). The type PARSER still accepts all five as input aliases for one
release cycle and normalizes each to the name it denotes
(`RETIRED_NUMERIC_ALIASES` in `parser.ts`), but an alias never reaches a
`Type` node and is never serialized back out.

</MemberCard>

<MemberCard>

### ParameterDefault {#parameterdefault}

```ts
type ParameterDefault = 
  | {
  kind: "value";
  value: number | string | boolean;
 }
  | {
  kind: "symbol";
  name: string;
 }
  | {
  kind: "empty-list";
 }
  | {
  kind: "empty-dictionary";
};
```

The default value of an optional function parameter, written after the
parameter type in a signature: `(x: number, factor: number = 2) -> number`.

- `value`: a number that a JavaScript `number` holds (a finite number,
  `NaN`, `+oo` or `-oo`), a string, or a boolean.
- `symbol`: a symbol, stored by name. The symbol itself is the default;
  it is not evaluated when the signature is parsed.
- `empty-list` and `empty-dictionary`: `[]` and `{}`.

A default is part of the type: the serializer prints it, so two signatures
that differ only by a default have different identity keys. Subtyping and
matching ignore it, as they ignore the parameter name.

</MemberCard>

<MemberCard>

### NamedElement {#namedelement}

```ts
type NamedElement = {
  name: string;
  type: Type;
  default: ParameterDefault;
};
```

</MemberCard>

<MemberCard>

### EffectLabel {#effectlabel}

```ts
type EffectLabel = 
  | "console"
  | "entropy"
  | "environment"
  | "fs_read"
  | "fs_write"
  | "network"
  | "random"
  | "scope"
  | "state"
  | "time";
```

An effect label: a member of a closed, engine-versioned enumeration.

Each label carries fixed metadata (impurity, observation vs action, frame
kind, handler-backed); consumers key on that metadata, never on the label
name. See `docs/EFFECTS-MODEL.md`.

The labels bear no implication relations to each other: the order on effect
sets is plain powerset inclusion, so the singletons are pairwise
incomparable (in particular `fs_write` does not imply `fs_read`).

</MemberCard>

<MemberCard>

### EffectSet {#effectset}

```ts
type EffectSet = "any" | EffectLabel[];
```

The effect set carried by a signature's arrow.

- `'any'` is the distinguished **top**: "unknown effects". Under union it
  absorbs, and no finite bound admits it.
- Otherwise a duplicate-free, alphabetically sorted list of labels, possibly
  **empty**.

An absent (`undefined`) `effects` field and `[]` denote the **same set**, ∅:
every semantic operation — subtyping, `pure`, the label predicates, union,
`matches()` — treats them identically. They differ only in **serialization**
(ruled 2026-08-01): absent is an empty specifier slot (effects were never
stated, and stay on the inferred track), while `[]` is the author's `pure`
and serializes back as ` pure`, so an explicit purity contract survives a
parse → serialize → re-declare round trip.

Build one with `normalizeEffectSet()` (inference: an empty result collapses
to `undefined`) or `normalizeStatedEffectSet()` (a stated set: an empty
result stays `[]`).

</MemberCard>

<MemberCard>

### TypeVariable {#typevariable}

```ts
type TypeVariable = {
  kind: "variable";
  name: string;
  value: true;
};
```

A universally quantified type variable (rank-1).

Only legal inside a function signature; declared and scoped by its arm's
`where` clause (the `typeParams` field of [FunctionSignature](#functionsignature)). A variable is
**atomic and opaque**: it is never reduced, distributed or collapsed, and it
is substituted away by instantiation at a call site.

</MemberCard>

<MemberCard>

### TypeVariance {#typevariance}

```ts
type TypeVariance = "in" | "out" | "inout";
```

How a parameterized NOMINAL type relates two of its applications
(`docs/TYPE-SYSTEM.md`).

Declared inside a type-parameter clause (`type tree<out T> = …`); the words
are contextual there and are never reserved. Only a nominal declaration
carries one — a transparent alias has no declaration-level variance, and a
`where` clause never does.

</MemberCard>

<MemberCard>

### TypeParameter {#typeparameter}

```ts
type TypeParameter = {
  name: string;
  kind: "value";
  bound: Type;
  variance: TypeVariance;
  protocols: string[];
};
```

One entry of a signature's `where` clause, or of a declared type's
type-parameter clause: the variable's name and its optional declared upper
bound.

The bound must be **ground** (no type variables) — validated when the
declared type is boxed. An unbounded variable's implicit bound is `any`.

</MemberCard>

<MemberCard>

### TypeParamsOption {#typeparamsoption}

```ts
type TypeParamsOption = 
  | string
  | ReadonlyArray<
  | string
  | {
  name: string;
  bound: Type | TypeString;
  variance: TypeVariance;
  kind: "value";
}>;
```

The `typeParams` option of a generic type declaration — an ALIAS
(`ce.declareType('Pair', 'tuple<T, T>', { alias: true, typeParams: ['T'] })`)
or a parameterized NOMINAL type
(`ce.declareType('tree', '…', { typeParams: [{ name: 'T', variance: 'out' }] })`).

Either clause TEXT (`'T, U: number'`, also accepted one entry at a time) or
pre-built parameters whose bound may be a type string. Every TEXT spelling
goes through the shared clause parser (`parseTypeParameterClause`); the
object-array form is validated directly by `normalizeDeclaredTypeParams`
(same rules: reserved names, duplicates, ground bounds).

</MemberCard>

<MemberCard>

### FunctionSignature {#functionsignature}

```ts
type FunctionSignature = {
  kind: "signature";
  args: NamedElement[];
  optArgs: NamedElement[];
  variadicArg: NamedElement;
  variadicMin: 0 | 1;
  effects: EffectSet;
  typeParams: TypeParameter[];
  result: Type;
};
```

</MemberCard>

<MemberCard>

### AlgebraicType {#algebraictype}

```ts
type AlgebraicType = {
  kind: "union" | "intersection";
  types: Type[];
};
```

</MemberCard>

<MemberCard>

### NegationType {#negationtype}

```ts
type NegationType = {
  kind: "negation";
  type: Type;
};
```

</MemberCard>

<MemberCard>

### ValueType {#valuetype}

```ts
type ValueType = {
  kind: "value";
  value: any;
};
```

</MemberCard>

<MemberCard>

### RecordType {#recordtype}

```ts
type RecordType = {
  kind: "record";
  elements: Record<string, Type>;
  optional: readonly string[];
};
```

A record is a collection of key-value pairs.

The keys are strings. A record type is CLOSED: a value of
`record{a: integer, b: string}` has exactly the keys `a` and `b`, and no
other key. A field can be OPTIONAL (`record{a: integer, b: string?}`): a
value can leave the key `b` out, and when the key is there, its value is a
`string`. A read of an optional field that the value leaves out gives the
absent value of a read (`Missing`, or `NaN` for a numeric field), as an
index out of range does.

Subtyping:

- Depth subtyping: `record{a: integer}` is a subtype of `record{a: real}`.
- No width subtyping: `record{a: integer, b: string}` is NOT a subtype of
  `record{a: integer}`, because the second type has no key `b`.
- A record type is a subtype of a record type that has every one of its
  keys, when each key that the second type requires is also required by
  the first: `record{a: integer}` and `record{a: integer, b: string}` are
  subtypes of `record{a: integer, b: string?}`.
- A record type is a subtype of `dictionary<V>` when every field type,
  optional fields too, is a subtype of `V`.

A program that must accept other keys takes a `dictionary`. The bare
primitive `record` holds every record.

Build a record type with [makeRecordType](#makerecordtype), which keeps the list of
optional keys in its normal form.

</MemberCard>

<MemberCard>

### ObjectType {#objecttype}

```ts
type ObjectType = {
  kind: "object";
  elements: Record<string, Type>;
};
```

The stored-field layout of an **object** type — the engine's one mutable
value kind.

Structurally this looks like [RecordType](#recordtype), and the two are read the
same way (an ordered map from field name to field type), but they behave in
opposite ways, and the difference is deliberate:

- An object type is **nominal**. This shape is only ever the definition
  (`def`) of a declared [TypeReference](#typereference): `type Person = object{…}`.
  Two object types with identical layouts are unrelated, because a store
  through one view would break the other's declared field types (write
  `1.5` into an `object{count: integer}` viewed as `object{count: number}`).
  The nominal reference is what supplies that opacity; this shape only
  carries the layout.
- Every field is a read/write position, so a field type is **invariant**:
  two object layouts relate only when every field type is mutually equal,
  and a type variable occurring in a field verifies only as `inout`.

The bare primitive `'object'` means "any object" and is the one common
bound every declared object type is a subtype of. It sits BESIDE `record`
in the lattice and is disjoint from it — sibling categories, one
immutable/structural, one mutable/nominal — and is deliberately not a
collection.

Spec: `docs/TYPE_SYSTEM_ROADMAP.md` Appendix B, "Declaring an object type",
"No subtyping between object types", "Generic object types" (ruling B13),
and the lattice bullet of "The rest of the system" (ruling B6).

</MemberCard>

<MemberCard>

### ArrayType {#arraytype}

```ts
type ArrayType = {
  kind: "array";
  elements: Type;
};
```

`array<T>` is the type of a mutable array whose cells hold values of type
`T`.

Every cell is a read/write position, so the cell type is **invariant**, as
the field type of an object is: `array<S>` is a subtype of `array<T>` only
when `S` and `T` are mutual subtypes, and a type variable in the cell type
verifies only as `inout`. Every `array<T>` is a subtype of the bare
primitive `'array'`; `array<any>` is one more invariant instance, not the
bare type.

An array type is disjoint from every collection type and from `object`: an
array is not a collection and is never broadcast over. The cell type alone
selects the storage (`arrayStorageKind()`).

Spec: `docs/plans/2026-11-25-mutable-arrays-spec.md`, sections 2 and 3.

</MemberCard>

<MemberCard>

### DictionaryType {#dictionarytype}

```ts
type DictionaryType = {
  kind: "dictionary";
  values: Type;
};
```

A dictionary is a collection of key-value pairs.

The keys are strings. The set of keys is also not defined as part of the
type and can be modified at runtime.

A dictionary is suitable for use as cache or data storage.

</MemberCard>

<MemberCard>

### CollectionType {#collectiontype}

```ts
type CollectionType = {
  kind: "collection" | "indexed_collection";
  elements: Type;
};
```

`CollectionType` is a generic collection of elements of a certain type.

- Indexed collections: List, Tuple
- Non-indexed: Set, Record, Dictionary

</MemberCard>

<MemberCard>

### ListType {#listtype}

```ts
type ListType = {
  kind: "list";
  elements: Type;
  dimensions: number[] | null;
  dimensionVariables: readonly (string | undefined)[];
};
```

The elements of a list can be accessed by their one-based index.

All elements of a list have the same type, but it can be a broad type,
up to `any`.

The same element can be present in the list more than once.

A list can be multi-dimensional. For example, a list of integers with
dimensions 2x3x4 is a 3D tensor with 2 layers, 3 rows and 4 columns.

</MemberCard>

<MemberCard>

### SymbolType {#symboltype}

```ts
type SymbolType = {
  kind: "symbol";
  name: string;
};
```

</MemberCard>

<MemberCard>

### ExpressionType {#expressiontype}

```ts
type ExpressionType = {
  kind: "expression";
  operator: string;
};
```

</MemberCard>

<MemberCard>

### NumericType {#numerictype}

```ts
type NumericType = {
  kind: "numeric";
  type: NumericPrimitiveType;
  lower: number;
  upper: number;
  lowerOpen: boolean;
  upperOpen: boolean;
};
```

</MemberCard>

<MemberCard>

### SetType {#settype}

```ts
type SetType = {
  kind: "set";
  elements: Type;
};
```

Each element of a set is unique (is not present in the set more than once).
The elements of a set are not indexed.

</MemberCard>

<MemberCard>

### BroadcastableType {#broadcastabletype}

```ts
type BroadcastableType = {
  kind: "broadcastable";
  elements: Type;
};
```

A `broadcastable<T>` is either a `T`, or a collection of `T` to which an
operation applies element-wise (runtime broadcasting). It is the static
type of an arithmetic result whose operand's collection-ness is not
statically visible. The node kind exists for every `T`, numeric or not.

What the collection arm is depends on `T`:

- When no value of `T` is a list (`T` is a number type, `boolean`,
  `string`, a tuple, `integer | missing`, …; `cannotHoldAList` in
  `subtype.ts`), the arm is `tensor<T>`, a tensor of any rank whose cells
  are `T` (a list node with `dimensions` `null`). So a matrix of numbers
  is a `broadcastable<number>`, a matrix of booleans is a
  `broadcastable<boolean>`, and a plain list of numbers, of booleans or
  of points is one too, read at rank 1. A `list<list<boolean>>` is not a
  `broadcastable<boolean>`: its rows may differ in length, so it is not
  a tensor.
- When `T` can hold a list (`any`, `value`, a type variable), the arm is
  the plain list `list<T>`, read by its elements: a `list<any>` is a
  `broadcastable<any>`.

A `T` (and any subtype of `T`) is a subtype of `broadcastable<T>`, and so is
any subtype of the collection arm (a tuple, a string and an abstract
`indexed_collection<T>` are not lists). It is *not* a subtype of `T` (it
may be a collection) nor of its collection arm (it may be a scalar). See
`subtype.ts` for the full relation (`broadcastCollectionArm` builds the
arm). Decided by the user on 2026-10-21 (decision D4 of
`docs/plans/2026-10-21-list-element-tensor-cell.md`, refined to keep the
node for every `T`).

</MemberCard>

<MemberCard>

### TupleType {#tupletype}

```ts
type TupleType = {
  kind: "tuple";
  elements: NamedElement[];
};
```

The elements of a tuple are indexed and may be named or unnamed.
If one element is named, all elements must be named.

</MemberCard>

<MemberCard>

### TypeReference {#typereference}

```ts
type TypeReference = {
  kind: "reference";
  name: string;
  alias: boolean;
  def: Type | undefined;
  typeParams: TypeParameter[];
  args: Type[];
  _varianceState: "deferred" | "verified";
  _varianceBlockedOn: string[];
  _sumOf: string;
  _sumVariants: {
     name: string;
     typeParams: string[];
    }[];
  _declOrigin: DeclarationOrigin;
  _minted: boolean;
};
```

Nominal typing

</MemberCard>

<MemberCard>

### DeclarationOrigin {#declarationorigin}

```ts
type DeclarationOrigin = {
  batch: number;
  statementId: unknown;
  firstRange: [start: number, end: number];
};
```

Which compilation unit and which declaring statement a registry record came
from — the runtime half of the redefinition discipline
(`docs/TYPE-SYSTEM.md`, "Mechanics").

A second declaration of a name with the SAME `batch` and a DIFFERENT
`statementId` is a within-unit redefinition and is refused; the same
`statementId` re-registering is the same statement declaring itself again
(one statement registers up to three times per batch — the static pre-pass
canonicalizes it, then the evaluation loop canonicalizes and evaluates it)
and is accepted.

`statementId` is an opaque IDENTITY token, compared with `!==` and never
inspected: the raw (uncanonicalized) name operand the `Declare*` handlers
thread from their canonical handler into their evaluate handler. It is typed
`unknown` so this engine-free module needs no expression type.

</MemberCard>

<MemberCard>

### Type {#type-3}

```ts
type Type = 
  | PrimitiveType
  | AlgebraicType
  | NegationType
  | CollectionType
  | ListType
  | SetType
  | BroadcastableType
  | RecordType
  | ObjectType
  | ArrayType
  | DictionaryType
  | TupleType
  | SymbolType
  | ExpressionType
  | NumericType
  | NumericPrimitiveType
  | FunctionSignature
  | ValueType
  | TypeVariable
  | TypeReference;
```

</MemberCard>

<MemberCard>

### TypeString {#typestring}

```ts
type TypeString = string;
```

The type of a boxed expression indicates the kind of expression it is and
the value it represents.

The type is represented either by a primitive type (e.g. number, complex, collection, etc.), or a compound type (e.g. tuple, function signature, etc.).

Types are described using the following BNF grammar:

```bnf
<type> ::= <union_type> | "(" <type> ")"

<union_type> ::= <intersection_type> (" | " <intersection_type>)*

<intersection_type> ::= <primary_type> (" & " <primary_type>)*

<primary_type> ::=  <primitive>
               | <tuple_type>
               | <signature>
               | <list_type>
               | <set>
               | <broadcastable>
               | <collection>
               | <type_reference>

(A reference to a user-declared type. The optional argument list applies a
GENERIC type alias (`Pair<integer>`); it is expanded eagerly into the
substituted alias body when the type is built, so an applied reference never
appears in a `Type`. The authoritative grammar lives with the parser in
`./parser.ts`.)

<type_reference> ::= ( "type" )? <identifier> ( "<" <type> ("," <type>)* ">" )?

<primitive> ::= "any" | "unknown" | <value-type> | <symbolic-type> | <numeric-type>

<numeric-type> ::= "number" | "complex" | "imaginary" | "real" | "rational" | "integer"

<value-type> ::= "value" | <numeric-type> | "collection" | "boolean" | "string"

<symbolic-type> ::= "expression" | "function" | "symbol"

<tuple_type> ::= "tuple<" (<name> <type> "," <named_tuple_elements>*) ">"
           | "tuple<" (<type> "," <unnamed_tuple_elements>*) ">" |
           | "tuple<" <tuple_elements> ">"

<tuple_elements> ::= <unnamed_tuple_elements> | <named_tuple_elements>

<unnamed_tuple_elements> ::= <type> ("," <type>)*

<named_tuple_elements> ::= <name> <type> ("," <name> <type>)*

<signature> ::=  <arguments> (" " <effects>)? " -> " <type>

<effects> ::= "pure" | "any" | <effect-label> (" " <effect-label>)*

(`pure` is the STATED empty set: the same set as an empty slot, and the
spelling that round-trips through serialization. See {@link EffectSet}.)

<effect-label> ::= "console" | "entropy" | "environment" | "fs_read"
           | "fs_write" | "network" | "random" | "scope" | "time"

<arguments> ::= "()"
           | "(" <argument-list> ")"

<argument> ::= <type>
           | <name> <type>

<rest_argument> ::= "..." <type>
           | <name> "..." <type>

<optional_argument> ::= <argument> "?"
           | <argument> "=" <default_value>

<default_value> ::= <value> | <identifier> | "[" "]" | "{" "}"

(An argument with a default value is optional; it is not combined with
`?`. The arguments with a default come before the optional arguments
without one. A default is not allowed on a rest argument, nor in a tuple
type. See {@link ParameterDefault}.)

<optional_arguments> ::= <optional_argument> ("," <optional_argument>)*

<required_arguments> ::= <argument> ("," <argument>)*

<argument-list> ::= <required_arguments> ("," <rest_argument>)?
           | <required_arguments> <optional_arguments>?
           | <optional_arguments>?
           | <rest_argument>

<list_type> ::= "list<" <type> <dimensions>? ">"
           | "vector<" (<type> <dimensions>? | <dimensions>) ">"
           | "matrix<" (<type> <dimensions>? | <dimensions>) ">"
           | "tensor<" <type> ">"
  Note: there is no `[type]` bracket shorthand; a list is always written with
  one of the `list`/`vector`/`matrix`/`tensor` heads. The authoritative
  grammar lives with the parser in `./parser.ts`.

<dimensions> ::= "^" <dimension>
           | "^(" <dimension> ("x" <dimension>)* ")"

<dimension> ::= <positive-integer_literal> | <identifier>
  An identifier in a length slot is a DIMENSION VARIABLE, declared by the
  enclosing `where` clause (`(a: vector<real^N>, b: vector<real^N>) -> real
  where N`) or by the type-parameter clause of the type being declared
  (`type permutation<N> = list<integer^N>`). The leading-length spellings
  `vector<3>` and `matrix<2x3>` take literals, or an `x`-joined group of
  two or more dimensions (`matrix<MxN>`); a bare identifier there is an
  element type (`vector<T>`).

(The `callback<…>` constructor of Design D was RETIRED by Design E
(`docs/TYPE-SYSTEM.md`): callback
slots are ordinary arrow types, admitted by COMPATIBILITY rather than
subtyping. The spelling now fails to parse, with a migration hint.)

<set> ::= "set<" <type> ">"

<broadcastable> ::= "broadcastable" ( "<" <type> ">" )?

<collection> ::= ( "collection" | "indexed_collection" ) ( "<" <type> ">" )?

<name> ::= <identifier> ":"

<identifier> ::= [a-zA-Z_][a-zA-Z0-9_]*

<positive-integer_literal> ::= [1-9][0-9]*
```

Examples of types strings:
- `"number"`    -- a simple type primitive
- `"(number, boolean)"` -- a tuple type
- `"(x: number, y:boolean)"` -- a named tuple/record type. Either all arguments are named, or none are
- `"collection<any>"` -- an arbitrary collection type, with no length or element type restrictions
- `"collection<integer>"` -- a collection type where all the elements are integers
- `"collection<(number, boolean)>"` -- a collection of tuples
- `"collection<(value:number, seen:boolean)>"` -- a collection of named tuples
- `"vector<boolean^32>"` -- a list type with a fixed size of 32 elements
- `"matrix<integer^(2x3)>"` -- an integer matrix of 2 rows and 3 columns
- `"tensor<integer^(2x3x4)>"` -- a tensor of dimensions 2x3x4
- `"number -> number"` -- a signature with a single argument
- `"(x: number, number) -> number"` -- a signature with a named argument
- `"(number, y:number?) -> number"` -- a signature with an optional named argument (can have several optional arguments, at the end)
- `"(number, number+) -> number"` -- a signature with a rest argument (can have only one, and no optional arguments if there is a rest argument).
- `"() -> number"` -- a signature with an empty argument list
- `"(number) random -> number"` -- a signature that may draw from the seeded random stream
- `"(number) random scope -> number"` -- a signature with two effect labels
- `"(number) any -> number"` -- a signature with unknown effects
- `"number | boolean"` -- a union type
- `"(x: number) & (y: number)"` -- an intersection type
- `"number | ((x: number) & (y: number))"` -- a union type with an intersection type
- `"(number -> number) | number"` -- a union type with a signature and a primitive type

</MemberCard>

<MemberCard>

### TypeCompatibility {#typecompatibility}

```ts
type TypeCompatibility = "covariant" | "contravariant" | "bivariant" | "invariant";
```

</MemberCard>

<MemberCard>

### TypeResolver {#typeresolver}

```ts
type TypeResolver = {
  get names: string[];
  forward: (name) => TypeReference | undefined;
  resolve: (name) => TypeReference | undefined;
  conformsTo: (type, protocol) => boolean;
};
```

A type resolver should return a definition for a given type name.

</MemberCard>

----

<MemberCard>

### COMPLEX\_INFINITY\_VALUE {#complex_infinity_value}

```ts
const COMPLEX_INFINITY_VALUE: Readonly<{
  complexInfinity: true;
}>;
```

The value carried by the type of the unsigned complex infinity `~oo`, which
has no JavaScript number to stand for it: `Infinity` and `-Infinity` are the
signed pair, and `NaN` is a different value altogether.

A value-literal type holds an arbitrary runtime value (see [`ValueType`](#valuetype)), so this frozen tagged object is that value. Test for it with
[`isComplexInfinityValue`](#iscomplexinfinityvalue), which reads the TAG: a `Type` node can be
rebuilt or re-frozen on its way through the parser and the reducers, so
object identity is not a reliable test.

</MemberCard>

----

<MemberCard>

### isComplexInfinityValue() {#iscomplexinfinityvalue}

```ts
function isComplexInfinityValue(v): v is Readonly<{ complexInfinity: true }>
```

True if `v` is the [`COMPLEX_INFINITY_VALUE`](#complex_infinity_value) sentinel, i.e. the
value of the `~oo` value-literal type. Reads the tag, never the identity.

##### v

`unknown`

</MemberCard>

<MemberCard>

### isOptionalField() {#isoptionalfield}

```ts
function isOptionalField(t, key): boolean
```

Whether `key` is an optional field of the record type `t`. A key that
`t` does not list is not optional: it is not a field.

##### t

`Readonly`\<[`RecordType`](#recordtype)\>

##### key

`string`

</MemberCard>

<MemberCard>

### hasRecordField() {#hasrecordfield}

```ts
function hasRecordField(t, key): boolean
```

Whether `key` is a field of the record type `t`, required or optional.
An own-property test: `Object.prototype` member names (`toString`) are
valid keys, and `key in` would find them on the prototype.

##### t

`Readonly`\<[`RecordType`](#recordtype)\>

##### key

`string`

</MemberCard>

<MemberCard>

### requiredFieldKeys() {#requiredfieldkeys}

```ts
function requiredFieldKeys(t): string[]
```

The keys of the record type `t` that every value has.

##### t

`Readonly`\<[`RecordType`](#recordtype)\>

</MemberCard>

<MemberCard>

### makeRecordType() {#makerecordtype}

```ts
function makeRecordType(elements, optional?): RecordType
```

A record type with the fields `elements`, of which the keys in `optional`
are optional. The list of optional keys is sorted, keeps only keys of
`elements`, and is left out when it is empty, so that two spellings of
one type have one structure.

##### elements

`Record`\<`string`, [`Type`](#type-3)\>

##### optional?

`Iterable`\<`string`, `any`, `any`\>

</MemberCard>

<MemberCard>

### listTensorRank() {#listtensorrank}

```ts
function listTensorRank(t): number | undefined
```

The rank of the list type `t`: the number of its axes when `t` is a
tensor with a dimension list (`vector<U>` is 1, `matrix<U>` is 2,
`tensor<U^(2x3x4)>` is 3), and `undefined` for a plain list (`list<E>`,
whose `dimensions` is absent) and for a tensor of unknown rank
(`tensor<U>`, whose `dimensions` is `null`).

##### t

`Readonly`\<[`ListType`](#listtype)\>

</MemberCard>
