Skip to content

The IR

The builder does not evaluate anything. It makes an expression: a tree of plain JSON data. The interpreter evaluates the tree. Other functions read the same tree: explain makes a trace, deps lists the reads, and serialize gives the JSON text.

The distance to the nearest other box797 characters of JSON
root.from("position")
  .others((e) => e._.subtract("position")._.length())
  .min()
{
  "tag": "app",
  "op": "min",
  "args": [
    {
      "tag": "let",
      "bind": {
        "$0": {
          "tag": "ref",
          "path": [
            "position"
          ]
        }
      },
      "body": {
        "tag": "each",
        "axis": {
          "t": "others"
        },
        "body": {
          "tag": "app",
          "op": "length",
          "args": [
            {
              "tag": "app",
              "op": "subtract",
              "args": [
                {
                  "tag": "var",
                  "name": "$0"
                },
                {
                  "tag": "ref",
                  "path": [
                    "position"
                  ]
                }
              ]
            }
          ]
        }
      }
    }
  ]
}

The chain others(...) binds the current value to a fresh name ($0), and the body reads that name with var. Thus the base value comes from the origin, and the field names of the body read at each target.

Kind Fields Value
lit value the value
ref path, at the field at the path, in the record at the address at
app op, args the op applied to the values of the arguments. For a method op, the first argument is the receiver.
let bind, body the body, with names bound to the values of the bindings
var name the value of a bound name
fn params, body a function. It is only a binding of let.
call fn, args the body of the bound function fn at this position, with the values of args for its parameters
rec fields a record of the values of the fields
each axis, body, at a list: the body at each target of the axis, from the key of the address at
fold axis, init, step, result, at a loop over the targets of the axis, in order. init gives the names and their first values, and step gives the next values at each target.
iterate limit, init, step, result, until a loop of at most limit steps (a whole number up to 100000, or a data limit { axis }, the number of targets of the axis). A true until stops it.
fix name, join, init, step a column with a value for each row. The rounds repeat step until no row changes. The join or or max moves a row up, and and or min moves a row down. The value is the row of the focus. It is of step B.
last name the value of the focus in the last round of the fix with the name
ext kind, data the value that the extension handler of kind gives

The first three kinds have the same shape as the expressions of the render project. Thus a render expression is also a Vex expression.

The special forms if, and, or and ifError are app nodes. The interpreter evaluates their arguments only when it needs them.

A binding of let can be a function: fn(params, body). call(name, ...args) applies it. Write a calculation once, and call it where you need it.

import { app, axes, call, each, evaluate, fn, let_, lit, ref, space, v } from "@mark1russell7/vex";
import { NumDomain } from "@mark1russell7/vex-domains";
const rows = space.array([{ w: 10 }, { w: 20 }, { w: 30 }]);
// The body reads the field w at the position of the call: here, at each target of the axis.
const weight = fn(["k"], app("multiply", ref("w"), v("k")));
const total = let_({ weight }, app("sum", each(axes.all, call("weight", lit(2)))));
evaluate(total, { space: rows, origin: "0", domains: [NumDomain] }); // => { ok: true, value: 120 }
  • The body evaluates at the position of the call. Thus a field reference of the body reads at the focus of the call.
  • The body sees the names of the place of its binding, not the names of the place of the call.
  • Each parameter gets the value of its argument. An argument that fails has an effect only where the body reads it.
  • A function cannot call itself or another binding of its let. Thus each call ends. A function of an outer let is in the scope.
  • A parameter, a binding or a name of a loop with the name of a function hides the function.
  • A function is not a value. v of a function, a call of a value and a call with the wrong number of arguments give #VALUE!.

Tier 2 puts the body at each call, in at most 10000 places of one program. A module prints one JavaScript function for each function. Refer to the rules FN.* of the specification.

An address is a list of moves. The moves apply in order, from the focus.

Move Goes to
{ t: "key", key } the key, or #REF!. key can be an expression that gives a text.
{ t: "index", i } the key at position i of the key order. i can be an expression that gives a number.
{ t: "other" } the other key of a space with two keys
{ t: "offset", d } a relative position in an array (one number) or a grid (two numbers)
{ t: "origin" } the origin of the evaluation
{ t: "parent" } the parent of the focus in a tree space

Vex does not simplify an address. For example, [other, other] in a space with three keys gives #REF!. A simplification to the empty address hides that error, so Vex keeps each move.

Axis Targets
{ t: "all" } each key
{ t: "others" } each key except the focus
{ t: "other" } the other key of a pair
{ t: "neighbors", n } the 4 or 8 neighbor cells of a grid
{ t: "children" }, { t: "ancestors" }, { t: "descendants" }, { t: "siblings" } the relations of a tree space. Refer to trees.
{ t: "window", from, to } the keys at the offsets from from to to, in an array or among siblings
{ t: "successors" }, { t: "predecessors" }, { t: "reachable" } the edges of a graph space
{ t: "table", name } each key of another table of the evaluation
{ t: "list", list } the keys of the items of the list that the expression list gives, in the order of the list
{ t: "reverse", axis } the targets of axis from the last to the first. The inner axis is not where, reverse or table.
{ t: "where", axis, test } the targets of axis where test gives true

The value of each is a list: one item for each target, with its key and its result. A let can bind a list, and a list op applies to its name. The axis list(expr) has the keys of the items of a list as targets, in the order of the list. The body reads the fields of each target.

import { app, axes, each, evaluate, let_, lit, ref, space, v } from "@mark1russell7/vex";
import { NumDomain } from "@mark1russell7/vex-domains";
const boxes = space.array([{ x: 30, w: 1 }, { x: 10, w: 2 }, { x: 20, w: 3 }]);
// The boxes in the order of x, and then the widths in that order.
const byX = let_({ sorted: app("sortBy", each(axes.all, ref("x"))) }, app("values", each(axes.list(v("sorted")), ref("w"))));
evaluate(byX, { space: boxes, origin: "0", domains: [NumDomain] }); // => { ok: true, value: [2, 3, 1] }
Op Value
sortBy(list) a list with the items in the order of their values, from the smallest. The values are numbers or texts. Equal values keep their order.
take(list, n) a list of the first n items
nth(list, i) the value of the item at the position i, from 0. A position after the last item gives #N/A.
setNth(list, i, value) a list with the value at the position i, from 0. The item keeps its key. A position after the last item gives #N/A.
drop(list, n) a list of the items after the first n items
append(list, other) a list of the items of list, and then the items of other
without(list, other) a list of the items of list whose key is not the key of an item of other
flat(list) a list of the items of the lists that are the values of the items of list, in order
get(list, key) the value of the first item with the key key. A key that no item has gives #N/A.

These ops skip error items, as each list op does. The option { strict: true } gives the first error. The axis reverse(list(expr)) gives the reverse order, and an error item of the list gives an error item for its target. A standalone module keeps each list as an array. Tier 2 gives a list op on a list with the code of the interpreter. It also gives the axis list, and tier 1 evaluates that axis over an error item.

The ops drop, append, without and flat build new lists, and each item keeps its key and its value. Thus a list can be a stack: append puts items on the top, take(stack, 1) is the top, and drop(stack, 1) removes it. without(list, seen) removes the keys that a search saw. A body of an axis can give a list, and flat joins these lists. A standalone module does not have these four ops yet, so it gives a reason.

import { app, axes, each, evaluate, ref, space } from "@mark1russell7/vex";
const tree = space.tree({ r: { n: 1 }, a: { n: 2 }, b: { n: 3 }, c: { n: 4 }, d: { n: 5 } }, { a: "r", b: "r", c: "a", d: "b" });
// The grandchildren of r: the lists of the children of each child, in one list.
const grandchildren = app("flat", each(axes.children, each(axes.children, ref("n"))));
evaluate(app("keys", grandchildren), { space: tree, origin: "r" }); // => { ok: true, value: ["c", "d"] }
evaluate(app("keys", app("without", grandchildren, each(axes.descendants, ref("n"), [{ t: "key", key: "b" }]))), { space: tree, origin: "r" }); // => { ok: true, value: ["c"] }

A name of fold or iterate can hold a list (LOOP.LIST). A step reads the old value at a key with get(list, key). Thus each item of the next list can read each item of the old list. A record that a step reads by key keeps its key in a field, because get takes the key as a value.

A literal can be a list (LIST.LITERAL). Its JSON form is the form of vexList, so the empty list can start a stack or a seen set. A standalone module gives a reason for these programs, and tier 1 evaluates them.

import { app, axes, each, evaluate, iterate, lit, ref, space, v, vexList } from "@mark1russell7/vex";
const ring = space.array([{ next: "1", n: 30 }, { next: "2", n: 10 }, { next: "0", n: 20 }]);
// Each step gives each item the old value of the item at the key in the field next.
const turn = (steps: number) => iterate(steps, { xs: each(axes.all, ref("n")) }, { xs: each(axes.all, app("get", v("xs"), ref("next"))) }, app("values", v("xs")));
evaluate(turn(1), { space: ring, origin: "0" }); // => { ok: true, value: [10, 20, 30] }
evaluate(turn(2), { space: ring, origin: "0" }); // => { ok: true, value: [20, 30, 10] }
evaluate(app("count", lit(vexList([]))), { space: ring, origin: "0" }); // => { ok: true, value: 0 }
evaluate(app("get", each(axes.all, ref("n")), lit("9")), { space: ring, origin: "0" }).ok; // => false

An array of a field or of a name is a list where a list op or the axis list needs a list (LIST.ARRAY). The key of each item is its position, from "0". A position without a value, or with null, gives an error item of #N/A. A domain or a function of the host with the op comes first, so each result of that op stays.

Op Value
indexOf(list, value) the position of the first item with the value, from 0, as nth counts. The value is a number, a text or a boolean. A value that no item has gives #N/A.
includes(list, value) true when an item equals the value by the op eq of the domain of the value, and else false. The walk stops at the first true. A value without eq gives #NAME?.
fill(n, value) a list of n items with the value. The keys are the positions. n is a whole number from 0 to 100000.
distinct(list) the first item of each value, in order, with its key. The values are numbers, texts or booleans.
group(list, keys) one item for each text of keys, in the order of its first position. Its value is the list of the items at its positions.
join(list, sep) the texts of the items, with the text sep between them. An empty list gives the empty text.

Thus a stack of a layout needs no functions of the host. The fractions, the keys of the slots and the bounds are names of the run. Without as, the body of the axis list reads the fields of each target, not the values of the items. Thus the fold below counts the items, and nth reads the value at each position.

import { app, axes, evaluate, fold, let_, lit, ref, space, v, type Expr } from "@mark1russell7/vex";
import { NumDomain, Vec2, Vec2Domain } from "@mark1russell7/vex-domains";
const items = space.array([{ key: "head" }, { key: "body" }, { key: "foot" }]);
const vars = { fr: [0.2, 0.3, 0.5], keys: ["head", "body", "foot"], bounds: new Vec2(300, 220), dir: new Vec2(0, 1), gap: 10 };
const run = (e: Expr, origin: string) => evaluate(e, { space: items, origin, domains: [Vec2Domain, NumDomain], vars });
// The length of the stacked axis without the gaps: 220 - 10 * (3 - 1) = 200.
const total = app("subtract", app("along", v("bounds"), v("dir")), app("multiply", v("gap"), app("subtract", app("count", v("fr")), lit(1))));
// The slot of an item is the position of its key. The offset adds f * total + gap for each fraction before the slot.
const step = app("add", v("at"), app("add", app("multiply", app("nth", v("fr"), v("i")), v("total")), v("gap")));
const offset = let_({ total, s: app("indexOf", v("keys"), ref("key")) }, fold(axes.list(app("take", v("fr"), v("s"))), { i: lit(0), at: lit(0) }, { i: app("add", v("i"), lit(1)), at: step }, v("at")));
["0", "1", "2"].map((k) => run(offset, k)); // => [{ ok: true, value: 0 }, { ok: true, value: 50 }, { ok: true, value: 120 }]
run(app("sum", app("take", v("fr"), lit(2))), "0"); // => { ok: true, value: 0.5 }
run(app("values", app("fill", lit(4), lit(0.25))), "0"); // => { ok: true, value: [0.25, 0.25, 0.25, 0.25] }

Tier 2 gives indexOf, includes, fill, distinct, group and join on a list. A standalone module gives a reason for includes, distinct, group and join. A list op of tier 2 on an array goes to tier 1, so each tier gives the same result.

The field as of each and fold gives names to the value of each item and to its index (AXIS.LIST.ITEM). It needs the axis list, also inside reverse and where.

  • as: [item] binds item to the value of the item of each target.
  • as: [item, index] also binds index to the position of the item, from 0, as nth counts (AXIS.LIST.INDEX). The error items do not count, and reverse does not change the index.
  • The names are visible in the body of each and in each step of fold (AXIS.LIST.SCOPE). The test of where, init and result do not see them.
  • An error item gives an error item for its target, and the body does not evaluate. In a fold, the error is the value of the fold.

To keep only some items, put the test in the body. The body gives a list of one item or an empty list, and flat joins these lists.

import { app, axes, each, evaluate, fold, lit, space, v } from "@mark1russell7/vex";
import { NumDomain } from "@mark1russell7/vex-domains";
const one = space.array([{ n: 0 }]);
const run = (e: Parameters<typeof evaluate>[0]) => evaluate(e, { space: one, origin: "0", domains: [NumDomain], vars: { ws: [3, 5, 2] } });
// Each value plus its index, and the sum of the values.
run(app("values", each(axes.list(v("ws")), app("add", v("w"), v("i")), undefined, ["w", "i"]))); // => { ok: true, value: [3, 6, 4] }
run(fold(axes.list(v("ws")), { s: lit(0) }, { s: app("add", v("s"), v("w")) }, v("s"), undefined, ["w"])); // => { ok: true, value: 10 }
// The values that are more than 2, in the order of the list.
const keep = app("if", app("gt", v("w"), lit(2)), app("fill", lit(1), v("w")), app("fill", lit(0), v("w")));
run(app("values", app("flat", each(axes.list(v("ws")), keep, undefined, ["w"])))); // => { ok: true, value: [3, 5] }

Tier 2 and a standalone module do not have these names yet. They give a reason, and tier 1 evaluates the program.

Does the box overlap another box?2393 characters of JSON
root.from("position")._.add("size")
  .others((e) =>
    e._.subtract("position")._.allPositive()._.and(
      e.from("position")._.add("size")._.subtract(e.origin().from("position"))._.allPositive()))
  .any()
{
  "tag": "app",
  "op": "any",
  "args": [
    {
      "tag": "let",
      "bind": {
        "$0": {
          "tag": "app",
          "op": "add",
          "args": [
            {
              "tag": "ref",
              "path": [
                "position"
              ]
            },
            {
              "tag": "ref",
              "path": [
                "size"
              ]
            }
          ]
        }
      },
      "body": {
        "tag": "each",
        "axis": {
          "t": "others"
        },
        "body": {
          "tag": "app",
          "op": "and",
          "args": [
            {
              "tag": "app",
              "op": "allPositive",
              "args": [
                {
                  "tag": "app",
                  "op": "subtract",
                  "args": [
                    {
                      "tag": "var",
                      "name": "$0"
                    },
                    {
                      "tag": "ref",
                      "path": [
                        "position"
                      ]
                    }
                  ]
                }
              ]
            },
            {
              "tag": "app",
              "op": "allPositive",
              "args": [
                {
                  "tag": "app",
                  "op": "subtract",
                  "args": [
                    {
                      "tag": "app",
                      "op": "add",
                      "args": [
                        {
                          "tag": "ref",
                          "path": [
                            "position"
                          ]
                        },
                        {
                          "tag": "ref",
                          "path": [
                            "size"
                          ]
                        }
                      ]
                    },
                    {
                      "tag": "ref",
                      "path": [
                        "position"
                      ],
                      "at": [
                        {
                          "t": "origin"
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    }
  ]
}

A program can go to a file, a database, a worker or another process. The JSON Schema of the IR is at ir.schema.json, and a test keeps it equal to the checks of parse. A language model can write a program from the schema, and llms.txt tells it where to start. serialize gives the JSON text, and parse checks the tree when it reads it back. A literal that is a domain value needs encode and decode in its domain.

compile(expr, options) changes the tree into a tree of functions, once. The program then evaluates at each origin of each space without a new walk of the tree. evaluate uses compile too, so the two cannot give different results.

deps(expr) gives each field read of a program, with its address, the axes around it and the address of each axis. A host can use the reads to evaluate a program again only when a field that it reads changes. Refer to the Lab to change a program as JSON.

A program can also be a document of coeval, the kernel of the family. Each language of the family writes its terms in this form. Thus one tool can read, check and show the programs of each language. toDocument gives the document of an expression, and fromDocument gives the expression of a document. compile, evaluate, explain and parse take a document too, and so do tiered, generate and emitModule of the compiler.

import { app, evaluate, fromDocument, lit, ref, space, toDocument } from "@mark1russell7/vex";
import { NumDomain } from "@mark1russell7/vex-domains";
const next = app("add", ref("n"), lit(1));
const doc = toDocument(next);
doc; // => { ok: true, value: { type: ["ops", "add"], value: [{ type: "ref", value: ["self", "n"] }, 1] } }
fromDocument(doc.ok ? doc.value : null); // => { ok: true, value: next }
evaluate(doc.ok ? doc.value : next, { space: space.array([{ n: 2 }]), origin: "0", domains: [NumDomain] }); // => { ok: true, value: 3 }

Each term is an envelope { type, value }. Another JSON value in the place of a term is a literal.

Expression Document
lit(v) v, or { type: "lit", value: v } when v has the shape of an envelope. At the root, a literal is always an envelope.
ref(path, at) { type: "ref", value: ["self", ...moves, ...path] }: a path from the position where the program evaluates
v(name) { type: "ref", value: ["names", name] }: a name of a let, a function, a loop or the caller
app(op, ...args) { type: ["ops", ...keys], value: args }. The keys are the name of the op, split at its dots.
let_(bind, body) { type: "let", value: { bind, body } }
fn(params, body) { type: "fn", value: { params, body } }
call(name, ...args) { type: "call", value: { fn: { type: "ref", value: ["names", name] }, args } }
rec(fields) { type: "record", value: fields }
each(axis, body, at, as) { type: "each", value: { axis, as, body, at } }. at is a reference from self with moves only. as is a list of texts.
fold(axis, init, step, result, at, as) { type: "fold", value: { axis, as, init, step, result, at } }
iterate(limit, init, step, result, until) { type: "iterate", value: { limit, init, step, until, result } }. A data limit dataLimit(axis) has the form { type: "size", value: { axis } }.
fix(name, join, init, step) { type: "fix", value: { name, join, init, step } }
last(name) { type: "last", value: name }
ext(kind, data) { type: ["ext", ...keys], value: data }

A move is { type: ["moves", kind], value }. The value of key or index is a term. A text key and a number position are fixed, and another term is a computed key or position, for example a term in an envelope. A literal of another kind gives #VALUE! at run time. The value of offset is its list of numbers, and the value of other, origin and parent is null. An axis is { type: ["axes", name], value: parameters }, for example { type: ["axes", "window"], value: { from: -1, to: 0 } }.

A document is JSON data. The value of a literal has the JSON form of serialize, so a domain value needs encode and decode. fromDocument does not throw. A document that is not valid gives #VALUE! with the reason and the location of the part, as a JSON Pointer. Refer to the rules DOC.* of the specification.

coeval is the core of Vex. VEX_WORLD gives the contract of each kind as data: its parts, the type of its data, the kinds of each position and its names. The static kit of the kernel checks each document by these contracts before fromDocument reads it (DOC.CHECK). The function deps finds the reads with refsOf.

The kernel is also the reference tier of Vex (EVAL.REFERENCE). kernelPlan evaluates a document with vexMachine, and the closure compiler and the loop compiler give its results. The method reference of a plan reads the document with the reference interpreter of the kernel, which compiles nothing. The method agree compares the tiers of the kernel with a tier that you give (EVAL.AGREE).

import { app, fromDocument, kernelPlan, ref, space } from "@mark1russell7/vex";
import { NumDomain } from "@mark1russell7/vex-domains";
// The contract of each permits only the fields axis, as, body and at.
const extra = { type: "each", value: { axis: { type: ["axes", "all"], value: {} }, body: 1, extra: 1 } };
fromDocument(extra).ok; // => false
const plan = kernelPlan(app("add", ref("n"), ref("n")), { domains: [NumDomain] });
const at = { space: space.array([{ n: 2 }]), origin: "0" };
plan.run(at); // => { ok: true, value: 4 }
plan.reference(at); // => { ok: true, value: 4 }
plan.agree(at, () => ({ ok: true, value: 4 })).ok; // => true