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

# Evaluation

<Intro>
Evaluating an expression is the process of determining the value of the
expression. This involves looking up the definitions of symbols and functions,
evaluating the arguments of functions, and applying the function to the
arguments.
</Intro>

## Evaluation Methods

**To evaluate an expression**, use the `evaluate()` function.

```live
// String expression
console.log(evaluate("3^2"));

// Expression object
const expr = parse("2 + 2");
console.log(evaluate(expr));
```


:::info[Note]
The `expr.value` property does not evaluate the expression. If the expression
is a literal, it returns the literal value. If the expression is a symbol, it
looks up the symbol in the current scope and returns its value.
:::

```live
parse("x").value = 314;
console.info(parse('42').value)
console.info(parse('x').value)
console.info(parse('2 + 2').value)
```

The `N()` function provides a numeric evaluation of its argument.

```live
console.log(evaluate("2\\pi"));
console.log(N("2\\pi"));
```

:::info[Note]
The `N()` and `evaluate()` functions are shorthands for the `expr.N()` and 
`expr.evaluate()` methods. They use a common shared compute engine instance.

The `expr.N()` method is a shorthand for `expr.evaluate({numericApproximation: true})`.
:::


### Compilation

An expression can be evaluated by compiling it to JavaScript using the `compile()` function.
The result includes a `run` function that can be called to evaluate the expression.


```live
// import { compile } from '@cortex-js/compute-engine';
const result = compile('2\\pi');
console.log(result.success ? 'compiled' : 'fallback');
console.log(result.run?.());
```


<ReadMore path="/compute-engine/guides/compiling/" > 
Read more about **compiling expressions** <Icon name="chevron-right-bold" />
</ReadMore>

## Asynchronous Evaluation

Some computations can be time-consuming. For example, computing a very large
factorial. To prevent the browser from freezing, the Compute Engine can
perform some operations asynchronously.

**To perform an asynchronous evaluation**, use the `expr.evaluateAsync()` method.

```js
try {
  const fact = parse('(70!)!');
  const factResult = await fact.evaluateAsync();
  console.log(factResult);
} catch (e) {
  console.error(e);
}
```

The `expr.evaluateAsync()` method returns a `Promise` that resolves to the result
of the evaluation. It accepts the same `numericApproximation` options as `expr.evaluate()`.

Several `evaluateAsync()` calls can run at the same time on one engine. Each
evaluation keeps the scopes it opens (the index of a `Sum`, the locals of a
`Block`) to itself, so two sums over the same index name evaluated together do
not see each other's index. One engine per concurrent evaluation is not
necessary.

```js
const a = ce.parse('\\sum_{k=1}^{100000} k').evaluateAsync();
const b = ce.parse('\\sum_{k=1}^{1000} k^2').evaluateAsync();
await Promise.all([a, b]);
// ➔ [5000050000, 333833500]
```

It is also possible to interrupt an evaluation, for example by providing the user
with a pause/cancel button.

**To make an evaluation interruptible**, use an `AbortController`
object and a `signal`.

For example, to interrupt an evaluation after 500ms:

```js
const abort = new AbortController();
const signal = abort.signal;
setTimeout(() => abort.abort(), 500);
try {
  const fact = parse('(70!)!');
  const factResult = await fact.evaluateAsync({ signal });
  console.log(factResult);
} catch (e) {
  console.error(e);
}
```

```live
:::html
<div class="stack">
  <div class="row">
    <button id="evaluate-button">Evaluate</button>
    <button id="cancel-button" disabled>Cancel</button>
  </div>

  <div id="output"></div>
</div>
:::js
const abort = new AbortController();

document.getElementById('cancel-button').addEventListener('click', 
  () => abort.abort()
);

document.getElementById('evaluate-button').addEventListener('click', async () => {
  try {
    document.getElementById('evaluate-button').disabled = true;
    document.getElementById('cancel-button').disabled = false;

    const fact = ce.parse('(70!)!');
    const factResult = await fact.evaluateAsync({ signal: abort.signal });
    document.getElementById('output').textContent = factResult.toString();
    
    document.getElementById('evaluate-button').disabled = false;
    document.getElementById('cancel-button').disabled = true;
  } catch (e) {
    document.getElementById('evaluate-button').disabled = false;
    document.getElementById('cancel-button').disabled = true;
    console.error(e);
  }
});

```



**To set a time limit for an operation**, wrap it in a span with
`ce.withTimeLimit(limit, fn)`. The `limit` is either a number of milliseconds
or an object `{ ms, label }`; everything evaluated inside the callback shares
one deadline.

```js
try {
  const fact = ce.parse('(70!)!');
  const result = ce.withTimeLimit({ ms: 1000, label: 'my-app:eval' }, () =>
    fact.evaluate()
  );
  console.log(result);
} catch (e) {
  console.error(e);
}
```

Spans nest by taking the tighter deadline, and a `CancellationError` reports
which span's budget expired through its `attribution` and `spans` fields. See
the [Execution Constraints](/compute-engine/guides/execution-constraints/)
guide for the full model, including the iteration and recursion budgets.
(The former `ce.timeLimit` property has been removed — spans are the only
way to arm a deadline.)

When an operation is canceled either because of a timeout or an abort, a
`CancellationError` is thrown. The class can be imported from the package
to distinguish cancellations from other errors:

```js
import { CancellationError } from "@cortex-js/compute-engine";
```

The time limit is respected by long-running operations including iteration
over large or infinite collections, big operators (`Sum`, `Product`,
`Reduce`), number-theoretic functions (`Factorial`, `Totient`, `Sigma0`…),
and numeric limit extraction (`Limit`, `NLimit`).

Numerical integration is an exception: rather than throwing, Monte Carlo
integration (`NIntegrate`) returns the estimate computed from the samples
taken so far, with a correspondingly larger error bound.


## Errors

An [`["Error"]`](/compute-engine/reference/core/#error) is a **value**, and it
propagates along the ordinary value path. If an operand that a function
evaluates strictly turns out to be an error, the whole expression evaluates to
that error — not to a frozen expression wrapped around it. The propagated
error carries an `["ErrorTrace"]` breadcrumb recording the operators it passed
through, so the failure site is still recoverable.

```ts
console.log(ce.parse('\\ln(\\text{a}) + 2').evaluate().json);
// ➔ ["Error",
//      ["ErrorCode", "'incompatible-type'", "'number'", "'string'"],
//      "'a'",
//      ["ErrorTrace", ["ErrorFrame", "'Ln'", 1], ["ErrorFrame", "'Add'", 1]]]
```

A **collection** is the exception: an error among its elements stays in place,
because a collection containing an error is still a well-formed collection.

An operand that is never evaluated cannot propagate anything. In a selection —
`["If"]`, `["Which"]` — or behind a short-circuit operator — `["And"]`,
`["Or"]` — the branch that is not taken is **dead code**, and an error inside it
never reaches the value:

```ts
console.log(ce.box(['If', 'True', 5, ['Divide', 'x']]).evaluate().json);
// ➔ 5
```

The diagnostic is not lost, only unevaluated: the boxed expression still holds
`["If", "True", 5, ["Divide", "x", ["Error", "'missing'"]]]`, so a tool that
walks the expression still reports it.

Errors do not spread past the tools that inspect them. `Type` reports
`"error"`, [`IsError`](/compute-engine/reference/core/#iserror) answers
`True`/`False`, and
[`Match`](/compute-engine/reference/control-structures/#match) decides on an
error subject — an `["Error", ...]` case destructures it, which is how a
failure is rescued.

`NaN` is **not** an error. It is an ordinary IEEE numeric value — it has its
own type, `nan`, under `number` — so it does not propagate this way: a
function applied to `NaN` runs and receives it, and is free to inspect it.

`NaN` is also **inexact**, so the exactness contract sends it down the numeric
branch: a numeric function of `NaN` numericizes under plain `evaluate()`,
without waiting for `.N()`, and the result is `NaN`.

```ts
console.log(ce.box(['Sin', NaN]).evaluate().json);
// ➔ "NaN"

console.log(ce.parse('\\ln(2)').evaluate().json);
// ➔ ["Ln", 2]      — an exact argument stays symbolic
```

A float operand makes the result a float, also when the value is a whole
number: the exact `0` divided by a float is the float `0.0`, and a float
exponent is kept.

```ts
console.log(ce.parse('0/2.5').evaluate().json);
// ➔ {"num": "0.0"}

console.log(ce.parse('3x^{2.0}').evaluate().json);
// ➔ ["Multiply", 3, ["Power", "x", {"num": "2.0"}]]   — not 3x^2
```


## Lexical Scopes and Evaluation Contexts

The Compute Engine supports
[lexical scoping](<https://en.wikipedia.org/wiki/Scope_(computer_science)>).

A **lexical scope** is a region of the code where a symbol is defined. 
Each scope has its own bindings table, which is a
mapping of symbols to their definitions. The definition includes the type
of the symbol, whether it is a constant and other properties.


An **evaluation context** is a snapshot of the current state of the Compute 
Engine. It includes the values of all symbols currently in scope and 
a chain of lexical scopes.

Evaluation contexts are arranged in a stack, with the current (top-most) 
evaluation context available with `ce.context`.

Evaluation contexts are created automatically, for example when a new scope is
created, or each time a recursive function is called.

Some functions may create their own scope. These functions have the `scoped`
flag set to `true`. For example, the `Block` function creates a new scope
when it is called: any declarations made in the block are only visible within the
block. Similarly, the `Sum` function creates a new scope so that the index
variable is not visible outside the sum.

### Binding

**[Name Binding](https://en.wikipedia.org/wiki/Name_binding) is the process of
associating a symbol with a definition.**

Name Binding should not be confused with **value binding** which is the process
of associating a **value** to a symbol.


To bind a symbol to a definition, the Compute Engine looks up the bindings table
of the current scope. If the symbol is not found in the table, the parent 
scope is searched, and so on until a definition is found.

If no definition is found, the symbol is not declared: it stays unbound, and
it is bound again each time the expression is evaluated, so it reads a
definition made later. Its type in the expression is the type that its uses
there require (`number` for the `x` of `x + 1`), or `unknown`. `ce.infer()`
declares such symbols with those types.

```mermaid
flowchart TD
  sym["symbol to bind"] --> cur["current scope"]
  cur -- "not found" --> parent["enclosing scopes,<br/>innermost first"]
  parent -- "not found" --> global["global scope<br/>(user definitions)"]
  global -- "not found" --> system["system scope<br/>(the standard library)"]
  system -- "not found" --> auto["no definition: the symbol<br/>is bound when it is evaluated"]
  cur -- found --> def["definition record"]
  parent -- found --> def
  global -- found --> def
  system -- found --> def
```

If the symbol is found, the definition record is used to evaluate the
expression. 

The definition record contains information about the symbol, such as its
type, whether it is a constant, and how to evaluate it.

There are two kind of definition records:
1. **Value Definition Record**: This record contains information about the
   symbol, such as its type and whether it is a constant.
2. **Operator Definition Record**: This record contains information about the
   operator, such as its signature and how to evaluate it.

Name binding is done during canonicalization. If name binding failed, the
`isValid` property of the expression is `false`.

**To get a list of the errors in an expression** use the `expr.errors` property.

<ReadMore path="/compute-engine/guides/expressions/#errors" > Read more about the
<strong>errors</strong> <Icon name="chevron-right-bold" /></ReadMore>

### Bound Variables and Assigned Values

Some operators **bind** a variable of their own: `D`, `Integrate`, `Limit`,
`Sum`, `Product`, `Solve`, and `Function` (its parameters), among others. The
variable such an operator binds is a **pure symbol** — only its declared type
and any in-scope assumptions apply. A **value** assigned to a same-named symbol
does **not** apply to it, and the variable stays symbolic in the result.

```js
ce.assign('x', 5);
ce.parse('\\frac{d}{dx} x^2').evaluate().print();
// ➔ 2x        (not 10 — the bound "x" ignores its assigned value)

ce.parse('\\int x^2 \\,dx').evaluate().print();
// ➔ x^3/3     (not 125/3)
```

Every **other** symbol in the expression is **free**: its value always applies
under evaluation. So with `a := 3` as well, `\frac{d}{dx}(a\,x^2)` is `6x` —
the free `a` resolves, the bound `x` does not.

`D`, `Integrate`, `Limit` and `Series` work on a formula, and their variable is
a variable of that formula. When a free symbol holds a formula in that
variable, they work on its value, and the variable's name in the value denotes
their variable. `ND`, `NIntegrate` and `NLimit` read the body of their function
argument in the same way. `Sum`, `Product` and the other operators that iterate
over an index do not: their index does not reach into the value of another
symbol.

```js
ce.assign('G', ce.parse('\\sin(x)'));
ce.parse('\\frac{d}{dx} G').evaluate().print();
// ➔ cos(x)

ce.parse('\\int G \\,dx').evaluate().print();
// ➔ -cos(x)

ce.parse('\\lim_{x \\to 0} G').evaluate().print();
// ➔ 0

ce.box(['ND', ['Function', 'G', 'x'], 1]).N().print();
// ➔ 0.5403023058595877

ce.box(['NIntegrate', ['Function', 'G', 'x'], 0, 1]).N().print();
// ➔ 0.45969769413186035

ce.parse('\\sum_{x=1}^{3} G').evaluate().print();
// ➔ 3sin(x)
```

A symbol that holds a formula can also be the whole operand, with no variable
written. The operand is then read as the formula, and the variable is chosen
from the symbols of the formula, as for a formula written in place. A symbol
that names a function (`Sin`, or `g` after `g(t) := t^2`) keeps its meaning:
its parameter is the variable.

```js
ce.parse('\\int_0^1 G').N().print();
// ➔ 0.45969769413186035 ± 0.00000000000000041

ce.parse('\\int G').evaluate().print();
// ➔ -cos(x)

ce.box(['Limit', 'G', 0]).evaluate().print();
// ➔ 0

ce.box(['ND', 'G', 1]).N().print();
// ➔ 0.5403023058595877

ce.box(['NIntegrate', 'G', 0, 1]).N().print();
// ➔ 0.45969769413186035
```

The same applies when the symbol is a part of the operand. A symbol that holds
a formula is not chosen as the variable: the variable is chosen from the
symbols of its formula and the other symbols of the operand. Assign the
formula before you parse or box the expression, because the variable is
chosen at that time.

```js
ce.parse('\\int_0^1 G + x').evaluate().print();
// ➔ 3/2 - cos(1)

ce.box(['ND', ['Multiply', 2, 'G'], 1]).N().print();
// ➔ 1.0806046117191754
```

To use an assumption instead of a value (which *does* inform simplification and
solving), use `ce.assume()` rather than `ce.assign()`.

### Temporary Values

`ce.withValues(values, fn)` gives symbols a value only while `fn` runs. When
`fn` returns or throws, each symbol gets back its earlier value and type.
While `fn` runs, every expression reads the values: an expression created
before the call, an expression created inside `fn`, and the body of a stored
function.

```js
ce.declare('a', 'real');
const expr = ce.parse('a + 1');
ce.withValues({ a: 3 }, () => expr.evaluate()).print();
// ➔ 4
expr.evaluate().print();
// ➔ a + 1

ce.parse('f(x) := x + a').evaluate();
ce.withValues({ a: 1 }, () => ce.parse('f(2)').evaluate()).print();
// ➔ 3
```

A value is checked as `ce.assign()` checks it: a value that the declared type
of the symbol does not admit throws. The value `undefined` gives the symbol no
value while `fn` runs, but a value that an assumption gives
(`ce.assume(ce.parse('a = 3'))`) still applies. A constant, a symbol bound to a
function definition, a value that is a function, and a value that `ce.assign()`
refuses throw before any symbol gets a value.

`ce.withValues()` can be called during an evaluation, for example in the
`evaluate` handler of an operator.
`fn` must be synchronous: the earlier values are put back when `fn` returns,
before a promise that it returns settles.

When putting back an earlier value fails, the error is thrown after every
other value is put back. If `fn` threw too, `ce.withValues()` throws an
`AggregateError`: its `errors` are the error of `fn` and the error of the
restore, in this order, and its `cause` is the error of `fn`.

### Function Calls Are Bound Lexically

A function call resolves its head (`f` in `f(3)`) through the binding the name
had where the call was created, in the same way a symbol is bound to its
definition during canonicalization. Declaring another function of the same
name in a scope that is current when the call is evaluated does not redirect
the call. Assigning a new function to the **original** binding does: a call
reads the function that its binding holds when it runs.

```js
ce.assign('f', ce.parse('x \\mapsto 2x'));
const call = ce.parse('f(3)');

ce.pushScope();
ce.declare('f', 'function');
ce.assign('f', ce.parse('x \\mapsto 100x'));
call.evaluate().print();
// ➔ 6      (the call keeps the binding it was created with)
ce.popScope();

ce.assign('f', ce.parse('x \\mapsto 3x'));
call.evaluate().print();
// ➔ 9      (the original binding now holds another function)
```

A call written before its function is defined is a **forward reference**. It
waits for a definition of the name in its own scope chain: evaluated while
the name has no value, it stays symbolic; evaluated after the definition, it
applies the function.

The scope chain is the scope the call was written in and the scopes around
it. A function of the same name that a scope pushed later declares is not
called. To call it, parse the expression in that scope:

```js
const call = ce.parse('h(2) + 1');
call.evaluate().print();
// ➔ 1 + h(2)   ("h" has no definition yet)

ce.assign('h', ce.parse('t \\mapsto 10t'));
call.evaluate().print();
// ➔ 21

ce.pushScope();
ce.declare('h', 'function');
ce.assign('h', ce.parse('t \\mapsto t + 1000'));
call.evaluate().print();
// ➔ 21         (the call reads the scope it was written in)
ce.parse('h(2) + 1').evaluate().print();
// ➔ 1003       (written in the pushed scope)
ce.popScope();
```

Compiled code calls the same function as the evaluation.

A function passed by name as a callback follows the same rule: written
before the function is defined, it reads the definition of the scope it was
written in, and with no definition there it stays symbolic.

```js
const squares = ce.parse('\\operatorname{Map}(h, [1, 2])');
ce.function('ListFrom', [squares]).evaluate().print();
// ➔ [h(1),h(2)]

ce.assign('h', ce.parse('t \\mapsto t^2'));
ce.function('ListFrom', [squares]).evaluate().print();
// ➔ [1,4]

ce.pushScope();
ce.declare('h', 'function');
ce.assign('h', ce.parse('t \\mapsto 100'));
ce.function('ListFrom', [squares]).evaluate().print();
// ➔ [1,4]      (the callback reads the scope it was written in)
ce.popScope();
```

A function whose body calls a function that is not defined yet gets its
result type and its effects again when that function is defined: with
`honest := () ↦ later()` and then `later := () ↦ Random()`, `honest` is
typed `() random -> real`.

Within one evaluation, the symbolic result of such a call is a value: it is
not resolved again when the name is assigned later in the same evaluation.
So with `h` declared by `ce.declare('h', 'function')` (an assignment in a
branch of an `If` to a name that no scope declares is the error
`assignment-to-undeclared-variable`),
`Sum(Block(If(k = 2, h := z ↦ 2z), h(k)), k, 1, 3)` is `10 + h(1)`: the
term `h(1)` was computed while `h` had no value, and the assignment at
`k = 2` does not reach it. A later evaluation resolves the stored result
again:

```js
const call = ce.parse('g(3)');
const result = call.evaluate();
// ➔ g(3)   ("g" has no definition yet)

ce.assign('g', ce.parse('x \\mapsto x^2'));
call.evaluate().print();
// ➔ 9
result.evaluate().print();
// ➔ 9      (a later evaluation resolves the stored result)
```

In a `Block`, a `DefineFunction` statement (the Epsil `function g(k) { … }`)
declares a local variable that holds the function. A call before the
statement is the error `read-before-declaration`. An `Assign` of a function
literal takes effect when it runs. A `Block`
evaluated directly by the host is a program: each of its statements is an
evaluation of its own, so a result stored by one statement is resolved again
when a later statement reads it.

### Default Scopes

The Compute Engine has a set of default scopes that are used to look up
symbols. These scopes are created automatically when the Compute Engine
is initialized. The default scopes include the **system** scope, and the **global** scope.

The **system** scope contains the definitions of all the built-in functions and
operators. The **global** scope is initially empty, but can be used to
store user-defined functions and symbols.

The **global** scope is the default scope used when the Compute Engine is
initialized.

Additional scopes can be created using the `ce.pushScope()` method.


### Creating New Scopes

**To add a new scope** use `ce.pushScope()`.

```ts
ce.assign('x', 100); // "x" is defined in the current scope
ce.pushScope();
ce.declare('x', 'integer'); // "x" is defined in the new scope
ce.assign('x', 500);
console.log(ce.expr('x').evaluate()); // 500
ce.popScope();
console.log(ce.expr('x').evaluate()); // 100
```

Without the `ce.declare()`, `ce.assign('x', 500)` in the new scope writes the
`x` of the outer scope, and `x` is `500` after the `ce.popScope()` too.

**To exit a scope** use `ce.popScope()`.

The names of an expression boxed after the `ce.popScope()` resolve in the
scopes that remain. An expression boxed while the scope was current keeps the
definitions of that scope.

### An Expression Reads the Scope It Was Boxed In

An expression resolves each name from the scope it was boxed in, for its type
and for its value. The scope that is current when the expression is evaluated
plays no part. A declaration made later in the scope the expression was boxed
in, or in one of its parents, is read; a declaration in a scope pushed after
the expression was boxed is not. To read the current scope, bind the
expression again with `ce.rebind()`:

```ts
ce.assign('x', 100);
const e = ce.expr(['Add', 'x', 1]);
ce.pushScope();
ce.declare('x', 'integer');
ce.assign('x', 500);
console.log(e.evaluate()); // 101
console.log(ce.rebind(e).evaluate()); // 501
const inner = ce.expr(['Add', 'x', 1]);
ce.popScope();
console.log(inner.evaluate()); // 501: it keeps the definitions of the popped scope
console.log(e.evaluate()); // 101
```


## Evaluation Loop

:::info

This is an advanced topic. You don't need to know the details of how the
evaluation loop works, unless you're interested in extending the standard
library and providing your own function definitions.

:::

Each symbol is **bound** to a definition within a **lexical scope** during 
canonicalization. This usually happens when calling `ce.expr()` or `ce.parse()`, 
or if accessing the `.canonical` property of a
non-canonical expression.

When a function is evaluated, the following steps are followed:

```mermaid
flowchart TD
  start["evaluate f(a, b, …)"] --> canon{"canonical?"}
  canon -- no --> err["error: canonicalize first"]
  canon -- yes --> lazy{"f is lazy?"}
  lazy -- yes --> assoc
  lazy -- no --> args["evaluate each argument, left to right<br/>a held argument, or a Hold, stays symbolic<br/>a Sequence result is spliced in; an empty one is dropped"]
  args --> assoc{"f is associative?"}
  assoc -- yes --> flat["flatten: f(f(a, b), c) → f(a, b, c)"]
  assoc -- no --> apply
  flat --> apply["apply f to the arguments"]
  apply --> result["return the result in canonical form"]
```

1. If the expression is not canonical, it cannot be evaluated and an error is
   thrown. The expression must be canonicalized first.

2. Each argument of the function are evaluated, left to right, unless the 
   function has a `lazy` flag. If the function is lazy, the arguments are not
   evaluated.

   1. An argument can be **held**, in which case it is not evaluated. Held
      arguments can be useful when you need to pass a symbolic expression to a
      function. If it wasn't held, the result of evaluating the expression would
      be used, not the symbolic expression.

      Alternatively, using the `Hold` function will prevent its argument from
      being evaluated. Conversely, the `ReleaseHold` function will force an
      evaluation.

   2. If an argument is a `["Sequence"]` expression, treat each argument of the
      sequence expression as if it was an argument of the function. If the
      sequence is empty, ignore the argument.

3. If the function is associative, flatten its arguments as necessary. \\[
   f(f(a, b), c) \to f(a, b, c) \\]

4. Apply the function to the arguments

5. Return the result in canonical form.
