man uiua/interpreter
How Uiua runs: stack, arrays and special-cased idioms
What does the Uiua interpreter actually do with a line like
/×↙3⍖°⊚ xs? Uiua is a stack-based array language. Every glyph is a function
on whole arrays, code runs from right to left, and there are no variables
inside an expression. That suggests a simple machine: push values, pop them
into a Rust function, push the result. The real one is close to that, with
two extra layers that decide a lot of the speed. A compile step rewrites
known glyph sequences into single instructions, and several primitives look
at their arguments, or at the function they were given, before choosing an
algorithm.
This article reads the source of Uiua 0.19.1 (tag 0.19.1 of
uiua-lang/uiua) and checks it with experiments on an Apple M2 Pro. Every
.ua file below runs with uiua run --no-format. Without the flag,
uiua run reformats the file in place before running it.
The short version
- Source is parsed and compiled to a tree of
Nodes. Since 0.14.0 the interpreter walks that tree directly; before, it ran bytecode. - The stack is a
Vec<Value>. AValueis an array of bytes,f64s, complex numbers, characters or boxes, and its data lives in a reference-counted, copy-on-write buffer. - Pure code with small constant inputs is evaluated at compile time.
- A peephole optimizer matches 45 patterns of adjacent nodes and
replaces them:
⇌⍆becomes one descending sort,⊢⍖becomes an O(n) scan,⧻◴becomes a count of unique values. - Some primitives check at run time what they were given:
⊕with exactly⧻counts without building groups,/with a primitive function runs a Rust loop, and arrays carry “sorted” flags that let later primitives skip work. - The rewrites interact.
⊸≠is rewritten into a duplicate before the split pattern gets to look at it, so the docs’ own splitting idiom⊜□⊸≠@\nruns about 10 times slower than⊜□⊸(≠@\n).
From glyphs to a tree
The compiler turns each line into nodes. The main kinds are Push (a
constant), Prim (a primitive function such as ⍖), Mod (a modifier such
as / or ⊕, with its function arguments as child nodes), Run (a
sequence), CallGlobal (a binding) and ImplPrim/ImplMod, which are
internal primitives that only the compiler can produce. Execution is one
match in run.rs:
let res = match node {
Node::Run(nodes) => nodes.into_iter().try_for_each(|node| self.exec(node)),
Node::Prim(prim, span) => {
self.with_prim_span(span, Some(prim), |env| run_prim_func(&prim, env))
}
Node::ImplPrim(prim, span) => self.with_span(span, |env| prim.run(env)),
Node::Mod(prim, args, span) => {
self.with_prim_span(span, Some(prim), |env| run_prim_mod(&prim, args, env))
}
// ...
Node::Push(val) => {
self.rt.stack.push(val);
Ok(())
}
The changelog for 0.14.0 (2024-12-20) says the compiler and interpreter were
“almost entirely rewritten to use a tree-based execution model rather than a
bytecode model”, to simplify optimizations and the derivation of inverses.
Inverses matter in Uiua: ° (un) and ⍜ (under) ask the compiler to derive
the inverse of a function, and a tree is easier to invert than a flat list
of instructions.
You can see the compiled tree. uiua build file.ua --output file.uasm
writes the assembly, nodes first, one per line, in execution order (so the
reverse of the source order).
Arrays and the stack
The stack is stack: Vec<Value> on the runtime struct. Value is an enum:
pub enum Value {
Byte(Array<u8>),
Num(Array<f64>),
Complex(Array<Complex>),
Char(Array<char>),
Box(Array<Boxed>),
// ...
}
An Array<T> is a shape, a data buffer and optional metadata. The buffer is
a CowSlice<T>: an EcoVec<T> (a reference-counted vector from the ecow
crate) plus u32 start and end indices, so splitting an array into rows can
share one allocation. Pushing a binding’s value twice copies a pointer, and a
primitive that wants to modify its argument in place only copies the data if
someone else still holds it.
The metadata holds a label, a map’s keys, and a byte of flags. Four flags
matter here: BOOLEAN, BOOLEAN_LITERAL, SORTED_UP and SORTED_DOWN.
They come back below.
Work done at compile time
Before running anything, the compiler tries to evaluate pure code. The
default PreEvalMode is Normal, which “tries to evaluate pure,
time-bounded constants and expressions at comptime”, and it skips code that
pushes a constant with more than MAX_PRE_EVAL_ELEMS, 1000 elements. The
limit is on constants in the code, not on intermediate results:
$ cat pre.ua
&p /+ ⇡100
&p /+ ⇡1e6
$ uiua build pre.ua --output pre.uasm && head -4 pre.uasm
{"push":4950.0}
["print",4]
{"push":499999500000.0}
["print",8]
Both sums, including the one over a million numbers, became constants. The
running program only prints them. This is also why timing experiments below
read their data from a file or generate it with gen: a benchmark over a
literal would measure nothing.
The peephole optimizer
After compiling, optimize_full runs over the tree. optimize.rs keeps a
list, UNSORTED_OPTS, of 45 patterns over adjacent nodes, written in execution
order. A few of them:
&((Rise, First), FirstMinIndex),
&((Fall, First), FirstMaxIndex),
&((Where, Len), LenWhere),
&((Deduplicate, Len), CountUnique),
&((Dup, Rise, Select), Sort),
&((Dup, Fall, Select), SortDown),
&((Sort, Reverse), SortDown),
&((Sort, First), FirstSort),
&((2, Pow), (Dup, Mul)),
(Rise, First) is ⊢⍏ in source order: grade up, then take the first
index. Grading sorts everything; FirstMinIndex scans once. The list also
holds larger optimizations written as Rust code, such as SplitByOpt for
partitioning a string by a delimiter and ByToDup, which turns ⊸f (by)
into a duplicate followed by f.
The .uasm output shows the rewrites. With the input read from stdin, so
nothing can be pre-evaluated:
$ cat o.ua
X ← &rs ∞ 0
⇌⍆ X
⊢⍖ X
⧻◴ X
⊕⧻ ⊸⊛ X
/× X
$ uiua build o.ua --output o.uasm && sed -n '6,16p' o.uasm
["SORT_DOWN",4]
{"call_global":[0,[0,1]]}
["FIRST_MAX_INDEX",6]
{"call_global":[0,[0,1]]}
["COUNT_UNIQUE",8]
{"call_global":[0,[0,1]]}
["DUP",10]
["CLASSIFY",9]
["GROUP",[[1,1,["LEN",12]]],11]
{"call_global":[0,[0,1]]}
["REDUCE",[[2,1,["MUL",14]]],13]
⇌⍆ became one SORT_DOWN, ⊢⍖ became FIRST_MAX_INDEX, ⧻◴ became
COUNT_UNIQUE, and ⊸⊛ became a plain DUP. ⊕⧻ and /× stay as they
are; their shortcuts are taken at run time.
The difference a rewrite makes is easy to measure. ⍜now(f) runs f
“under” the clock: it reads the time, runs f, reads the time again and
leaves the difference in seconds. ◌ drops f’s result:
$ cat fast.ua
Ms ← ÷100 ⁅ ×1e5
X ← ⌊×1000 gen 1e6 42
S ← &fras "lines.txt"
&p $"⊢⍖ _ ms" Ms ⍜now(◌⊢⍖) X
&p $"⊏0⍖ _ ms" Ms ⍜now(◌⊏0⍖) X
&p $"⊕⧻⊸⊛ _ ms" Ms ⍜now(◌⊕⧻⊸⊛) X
&p $"⊕(+0⧻)⊸⊛ _ ms" Ms ⍜now(◌⊕(+0⧻)⊸⊛) X
&p $"/+ _ ms" Ms ⍜now(◌/+) X
&p $"/(++0) _ ms" Ms ⍜now(◌/(++0)) X
&p $"⊜□⊸≠@\\n _ ms" Ms ⍜now(◌⊜□⊸≠@\n) S
&p $"⊜□⊸(≠@\\n) _ ms" Ms ⍜now(◌⊜□⊸(≠@\n)) S
$ uiua run --no-format fast.ua
⊢⍖ 0.86 ms
⊏0⍖ 19.38 ms
⊕⧻⊸⊛ 44.16 ms
⊕(+0⧻)⊸⊛ 100.71 ms
/+ 0.98 ms
/(++0) 533.75 ms
⊜□⊸≠@\n 16.54 ms
⊜□⊸(≠@\n) 1.65 ms
X is a million random integers below 1000; lines.txt holds 100,000
numbers, one per line (577,780 bytes). A second run kept every pair in the
same order. ⊢⍖ and ⊏0⍖ both return the index of the
largest value, and the rewritten one is 22 times faster, because it never
sorts. ⊏0⍖ means “select item 0”, which is the same thing to a person,
but the optimizer only compares node sequences.
Fast paths inside primitives
Some shortcuts can’t be decided at compile time, because they depend on the data, or they are easier to write inside the primitive.
Group with a simple function. ⊕ (group) is implemented by
collapse_groups in groups.rs. Before building any groups it looks at its
function:
match &f.node {
Prim(First, _) => { /* first row of each group */ }
Prim(Last, _) => { /* last row of each group */ }
Prim(Len, _) => {
// ...
env.push(lens(&indices.data));
return Ok(());
}
_ => {}
}
For ⧻, lens counts the group indices in a HashMap and writes the counts
into a list of f64. No group is ever materialised. ⊕(+0⧻) computes the
same numbers, but its function is a Run of three nodes, so it falls through
to the general path, which builds every group as an array and runs the
function on each one through the interpreter. In the experiment that is 101
against 44 ms for a million values in 1000 groups. The changelog lists the
⧻, ⊢ and ⊢⇌ cases for group and partition under 0.11.0 (2024-06-02).
Reduce with a primitive. reduce_impl asks whether its function is a
single primitive (possibly flipped). For numbers it then calls a macro-made
reduce_nums with a fast_reduce loop for +, -, ×, ∨, ↧ and ↥.
Anything else goes to generic_reduce, which calls the function through the
interpreter once per element: /(++0) took 534 ms where /+ took 1 ms.
Sorted flags. ⍆ marks its result SORTED_UP. Several primitives check
the flag first. ⊛ (classify) and ◴ (deduplicate) on a flagged array
compare each row with the previous one instead of hashing; ⍏ (rise) on an
array flagged SORTED_UP returns 0, 1, 2, ... without sorting; /↥ (max)
on a flagged list reads the last element.
Sorting by storage. ⍆ on a list of bytes is a counting sort over 256
buckets (since 0.16.0). On a list of f64 it calls rayon’s
par_sort_unstable_by, which its docs describe as based on pattern-defeating
quicksort. On rows of a
table it runs Uiua’s own introsort, with insertion sort for 20 rows or fewer,
heapsort when the recursion gets too deep, and rayon::join to sort the two
halves on different threads once a half has more than 2,000 rows. ⍏ and ⍖ sort a list of indices with
rayon’s par_sort_by, which is stable, so equal values keep their index
order.
When rewrites get in each other’s way
The partition docs split a string at spaces with ⊸≠ and ⊜□. ≠ makes
a mask, ⊸ keeps the string under it, and ⊜ cuts the string into
runs. SplitByOpt exists for exactly this, replacing mask and partition with
an ImplMod that scans for the delimiter and slices the string without
building a mask. It looks for any of these node sequences (paraphrased from
the Rust match arms):
[Mod(By, [Ne]), Partition(f), ..]
[Mod(By, [Mask]), Not, Partition(f), ..]
[Dup, Push(delim), Ne, Partition(f), ..]
[Dup, Push(delim), Mask, Not, Partition(f), ..]
⊸≠@\n compiles to Push("\n") followed by By(Ne). But ByToDup comes
earlier in the optimization list, and the loop applies the first pattern that
matches anywhere in the line. It rewrites ⊸≠ with its constant argument
into Push("\n"), Dip(Dup), Ne, which matches none of the four. With
parentheses, ⊸(≠@\n) is By around a function with one argument, ByToDup
turns it into Dup, Push, Ne, and that is the third pattern:
$ cat sb.ua
S ← &rs ∞ 0
⊜□ ⊸≠@\n S
⊜□ ⊸(≠@\n) S
$ uiua build sb.ua --output sb.uasm && sed -n '/call_global/,/^$/p' sb.uasm
{"call_global":[0,[0,1]]}
{"push":[[],"\n"]}
["DIP",[[1,2,["DUP",4]]],4]
["NE",3]
["PARTITION",[[1,1,["BOX",6]]],5]
{"call_global":[0,[0,1]]}
{"push":[[],"\n"]}
["SPLIT_BY_SCALAR",[[1,1,["BOX",10]]],9]
In the timing run above that is 16.5 against 1.7 ms for 100,000 lines.
The deprecated ≠@\n . (with ., duplicate) also produces
SPLIT_BY_SCALAR. The fast path pays off most with □: split_by has a
special case that boxes each piece directly. With any other function, such as
⋕ to parse numbers, it still calls the function once per piece through the
interpreter, and that call costs more than the mask did.
Curious facts
uiua runformats the file before running it, unless you pass--no-format. A file withX ← 1andLonger ← 2on two lines comes back with the arrows lined up.ⁿ2 xis compiled to×.x(duplicate, multiply),ⁿ3to two multiplications andⁿ¯1to⨪(reciprocal), all in the same pattern list.&rs ∞ 0(read stdin to the end) goes to Rust’sread_to_end, so it reads everything. A 589,095-byte file piped in came back as 589,095 characters.- The interpreter’s own tracer,
uiua run --time-instrs, prints one line per executed node. For⊜⋕over 100,000 lines it printed a⋕line for every input line, one interpreted call each. - Group’s length fast path builds its counts with a
HashMapkeyed by group index, although the indices are dense numbers from 0 that a plain list would hold.
History
- 0.0.17 (2023-10-07):
⍖(fall) is added. - 0.0.23 (2023-10-25):
⊢⍏,⊢⇌⍏,⊢⍖and⊢⇌⍖are optimized to O(n). - 0.11.0 (2024-06-02): group and partition get fast paths for
⧻,⊢and⊢⇌;⧻◴is optimized. - 0.14.0 (2024-12-20): tree-based execution replaces bytecode; common partition patterns are optimized.
- 0.16.0 (2025-05-18):
⍆on lists of bytes uses counting sort. - 0.18.0 (2026-02-05):
⊢⍆and⊣⍆become O(n);.(duplicate) and:(flip) are deprecated in favour of⊸,˙,⟜∘and˜. - 0.19.1 (2026-09-03): the version read here.
Sources
All at tag 0.19.1 of https://github.com/uiua-lang/uiua:
- Node execution: src/run.rs#L473, the stack at src/run.rs#L45
Value: src/value.rs#L29;Arrayand its flags: src/array.rs#L39, src/array.rs#L264CowSlice: src/cowslice.rs#L30- Pre-evaluation: src/compile/pre_eval.rs#L13; where optimizations run: src/compile/mod.rs#L577
- Pattern list: src/compile/optimize.rs#L103; ordering: #L151;
SplitByOpt: #L445;ByToDup: #L498 - Group and its fast paths: src/algorithm/groups.rs#L543, #L771;
split_by: #L15 - Reduce: src/algorithm/reduce.rs#L24, #L397
- Classify and deduplicate: src/algorithm/monadic/mod.rs#L1415, #L1531
- Rise, fall and the row introsort: src/algorithm/monadic/sort.rs#L57, #L397; list sorts: src/array.rs#L1049, #L1124
&rson stdin: src/sys/mod.rs#L844, src/sys/native.rs#L410- Primitive docs (sort, partition, by): parser/src/defs.rs
- Changelog: changelog.md
- rayon 1.10.0 (the version in Uiua’s
Cargo.lock),par_sort_bydocs: https://docs.rs/rayon/1.10.0/rayon/slice/trait.ParallelSliceMut.html
grep -rl /lib/uiua/interpreter/
ls uiua/
- draft Numbers in Uiua: everything is a floatUiua shows one number type, the IEEE double, and stores a second one, the byte; what that means for integers, indices, counts, printing, parsing, NaN and hash maps in Uiua 0.19.1.