Trust: a translator from Typst to RUST

Inspired by nuitka, trust translates a single .typ file into a standalone program, or a Typst package into a Rust crate (as a native typst module that can be imported), since the Typst compiler is itself a Rust program. Generated code drives the very libraries the interpreter runs on, typst-library’s Value, Func, and Content, and the same layout and export pipelines. So far, I have not applied any advanced optimizations to the generated code, yet early benchmarks show an approximately 2× speedup for cetz

coverage: On the official typst tests/suite corpus, all 3696 comparison cases currently produce results identical to the interpreter.

repo: GitHub - liquidhelium/trust: a translator from Typst to RUST. · GitHub

(Note on “standalone program”: You may be confused about why one would want to turn a Typst document into a standalone program, since normally the same source code is the same document, and speeding up the compilation of the same document seems strange. But in fact, you can read the --inputs passed to the Typst CLI through the sys.inputs dictionary, so it is actually possible to use one program to generate different documents. I think people who need to generate a large number of similar PDFs from templates might need this.)

Edit: Actually, it seems that what I said really wasn’t very clear. Here, the Rust crate generated by trust is not designed to be called from Rust; rather, it is specifically intended to be added to Typst’s library as a native module and can be imported via #import ....

5 Likes

Hi! I have a few questions about the benchmark. Specifically, this part:

1. Is bench.sh up to date?

Running bash bench.sh triggers an error.

bash bench.sh
$ bash bench.sh
workload: /tmp/trust-bench/stress.typ
golden:   /home/***/typst (typst 0.15.1 (9dfd3a08))
    Finished `release` profile [optimized] target(s) in 0.18s
dependency merged into translation: @preview/cetz:0.5.3 (entry src/lib.typ)
dependency merged into translation: @preview/oxifmt:1.0.0 (entry lib.typ)
generated prog (47 module files, 51 embedded files)
    Updating crates.io index
error: failed to get `trust-runtime` as a dependency of package `stress_program v0.0.0 (/tmp/trust-bench/prog)`

Caused by:
  failed to load source for dependency `trust-runtime`

Caused by:
  unable to update /tmp/trust-bench/prog/vendor/trust-runtime

Caused by:
  failed to parse manifest at `/tmp/trust-bench/prog/vendor/trust-runtime/Cargo.toml`

Caused by:
  error inheriting `comemo` from workspace root manifest's `workspace.dependencies.comemo`

Caused by:
  failed to find a workspace root

It looks like that trust a.typ --compile against an empty a.typ does not work either.

$ touch a.typ
$ ./target/release/trust translate a.typ --compile
generated ./a-program (2 module files, 1 embedded files)
error: current package believes it's in a workspace when it's not:
current:   /workspaces/trust/a-program/Cargo.toml
workspace: /workspaces/trust/Cargo.toml

this may be fixable by adding `a-program` to the `workspace.members` array of the manifest located at: /workspaces/trust/Cargo.toml
Alternatively, to keep it out of the workspace, add the package to the `workspace.exclude` array, or add an empty `[workspace]` table to the package's manifest.

2. How about typst-py?

The python package typst makes it possible to reuse the Typst compiler in memory.

I can’t execute bench.sh successfully, but it did create /tmp/trust-bench/stress.typ.
On my machine, compiling stress.typ with typst-py is 9.1 times faster than compiling it with typst CLI:

$ uv run bench.py
typst-py 10 runs: 787 ms
typst CLI 10 runs: 7164 ms
bench.py
[project]
name = "py"
version = "0.1.0"
requires-python = ">=3.14"
dependencies = [
    "typst>=0.15.2",
]
from collections.abc import Generator
from contextlib import contextmanager
from pathlib import Path
from subprocess import run
from time import perf_counter

import typst

N = 10


@contextmanager
def timeit(*, title: str) -> Generator[None]:
    start = perf_counter()
    yield
    end = perf_counter()
    print(f"{title}: {(end - start) * 1000:.0f} ms")


compiler = typst.Compiler()

doc = Path("/tmp/trust-bench/stress.typ").read_bytes()


with timeit(title=f"typst-py {N} runs"):
    for _ in range(N):
        pdf = compiler.compile(input=doc)

with timeit(title=f"typst CLI {N} runs"):
    for _ in range(N):
        run(
            ["typst", "compile", "-", "-", "--format=pdf", "--ignore-system-fonts"],
            input=doc,
            check=True,
            capture_output=True,
        )
2 Likes

Thanks for your report! bench.rs is indeed outdated, as I changed the runtime crate to use workspace dependencies and forgot that it would be copied into the generated crate. Now I fixed the bug.

As for typst-py, 9.1x seems to comes from the warm compile. Specifically, it’s these two lines:

compiler = typst.Compiler()                             # ← created once, outside the timed region
doc = Path("/tmp/trust-bench/stress.typ").read_bytes()  # ← the identical input for all N runs

typst.Compiler() holds the world (font book, source/package storage), and typst’s memoization caches (comemo) live in process-global state. So in your loop, iteration 1 pays a full cold compile, and iterations 2..N are largely served from persistent caches.

I reproduced this with the same stress.typ and the same code and find that, on my machine, first compile takes 715 ms, subsequent compiles 24–26 ms each, a ~30× warm/cold split. Your own total decomposes the same way.

The CLI side of your script is the opposite, every typst invocation is a fresh process, so each of the 10 runs pays in full.

Our 2x is a different scenario, where both columns is cold compilation. A warm in-process compiler is legitimately faster at recompiling the same document. If you want the warm-vs-warm comparison, the trust analog is a long-lived host embedding the translated package crate. (that benchmark doesn’t exist yet.)

2 Likes