Skip to content

Split typst-library to improve compile times #5664

Closed as not planned
Closed as not planned

Description

@01mf02

In this issue, I would like to propose a path towards splitting typst-library into two smaller parts, with the goal of decreasing Typst's build time.

Current Situation

A few months ago, @laurmaedje has performed a relatively large split of Typst into multiple crates #5302. To quote from his post, the crate dependency structure looks like this:

        macros ─────┐     ┌─ kit ───────────────────┐
                    │     ├─ eval ────┐         ┌─ cli
utils ─ syntax ─ library ─┼─ layout ──┼─ typst ─┤
          │               ├─ realize ─┤         └─ ide
timing ───┘               ├─ render ──┤
                          ├─ svg ─────┤             
                          └─ pdf ─────┘

As we can see, there is now a rather central crate, namely typst-library, on which everything to the right of it depends. Unfortunately, typst-library can take significant amounts of time to compile (on my machine about 15 seconds), which is --- at least for me --- significantly impeding my productivity.
I talked about this to @laurmaedje, and while he said something like "welcome to the life of a Typst developer", I felt motivated to change that life for the better.

I propose to split typst-library in two, namely typst-library and typst-libext (or something like that, modulo bikeshedding), such that the crate dependency graph looks as follows:

        macros ─────┐     ┌─ kit ─────────────────────────────┐
                    │     ├─ eval ──────────────┐         ┌─ cli
utils ─ syntax ─ library ─┼─ libext ── layout ──┼─ typst ─┤
          │               ├─ realize ───────────┤         └─ ide
timing ───┘               ├─ render ────────────┤
                          ├─ svg ───────────────┤             
                          └─ pdf ───────────────┘

This should reduce compile time, because many parts from typst-library will be moved to typst-libext, which can compile in parallel with other crates that depend on typst-library, such as typst-pdf. Furthermore, modifying code in typst-libext will trigger recompilation of significantly less crates than now.

Research

First, I tried to isolate a minimal subset of typst-library by starting from an empty crate, then adding parts of typst-library to it until reaching a natural "cut point". My hope was that we could split out the largest module in typst-library, namely typst-library::foundations, and make it into a separate crate typst-foundations.
This approach failed spectacularly.

Why?Among other, foundations contains a Value type that refers to Content, which is closely coupled to TextElem, and TextElem itself contains also lots of references to other types in typst-library, so you quickly end up including more and more types into your "small" crate that becomes larger and larger and larger. One particularly nasty type is Tiling (previously called Pattern), because Tiling internally contains a Frame, which is a very low-level primitive that depends on so many other types. Once I realised this (and after drowning in a sea of red compile errors), I gave up my first approach.

My second approach was to attack typst-library from the outside layer, by starting from the original typst-library (instead of from zero as before), then taking away things until I could not progress further. This approach turned out to cause much less friction. I was able to identify a number of types that could be split out from typst-library:

  • layout::{columns, grid, layout_, measure_, repeat, stack}
  • loading
  • math::{cancel, matrix, op, underover, ClassElem}
  • model::{bibliography, cite, enum_, list, outline, quote, reference, table, terms}

There is also potential for splitting out model::{figure, footnote} and text::raw.
FigureElem and FootnoteElem are only referenced a single time in introspection::counter, and RawElem is referenced a single time in foundations::value.
More about this later.

Packed Trouble

Now let us suppose that we move the aforementioned types from typst-library into a new crate, say typst-libext (for extension). When I tried this with StrongElem (because it's a relatively small element in terms of code size), I hit a Rust compilation error, saying that I could not impl Show for Packed<StrongElem> because Packed is defined outside the current crate (namely in typst-library, not in typst-libext). It struck me like a thunder. The orphan rule! All is lost. For one day, I contemplated about the futility of human endeavour, and found some consolation in my defeat.

To explain this error: There are many traits implemented for elements, such as Show, ShowExt, and Figurable. An element declares which of these traits it supports, by using a macro as in #[elem(Show, Figurable)]. These traits are always implemented not on an element E itself, but on its packed version, Packed<E>. The Packed type contains some meta information about an element, like a potential label, its position in the source code (span). If we could implement traits directly on elements, like impl Show for StrongElem, then we could easily move StrongElem out of typst-library. But because we have to impl Show for Packed<StrongElem>, we are in trouble.

The next day, it itched me to try something new: Let us look at the definition of the Show trait:

/// Defines a built-in show rule for an element.
pub trait Show {
    /// Execute the base recipe for this element.
    fn show(&self, engine: &mut Engine, styles: StyleChain) -> SourceResult<Content>;
}

This is always implemented for Packed<E>, so &self has type Packed<E>. Couldn't we introduce a new trait that makes this explicit?

/// Defines a built-in show rule for an element.
pub trait ShowPacked: NativeElement {
    /// Execute the base recipe for this element.
    fn show_packed(this: &Packed<Self>, engine: &mut Engine, styles: StyleChain) -> SourceResult<Content>;
}

OK, that was not too hard. But can we make it such that if we have impl ShowPacked for E, then we get impl Show for Packed<E>?

impl<T: ShowPacked> Show for Packed<T> {
    /// Execute the base recipe for this element.
    fn show(&self, engine: &mut Engine, styles: StyleChain) -> SourceResult<Content> {
        ShowPacked::show_packed(self, engine, styles)
    }
}

YES! It works! I would have bet that this would conflict with existing implementations of Show for Packed<E>. But it doesn't. I do not completely understand why, but it is the case.

Based on this approach, I was able to impl ShowPacked for StrongElem in typst-libext. After that, it was smooth sailing: It sufficed to extend typst_library::LibraryBuilder so that we can pass it a custom module to include in its standard library, then creating a module in typst-libext that contained only StrongElem, then chaining these two parts together in typst-cli. That allowed me to compile a Typst document that uses StrongElem defined outside of typst-library!

This is exciting, because it allows us to define elements outside of typst-library, meaning that compilation of such elements will be much faster than now, where we always have to recompile the whole of typst-library and everything depending on it.

Dynamic Linking

I still have to touch on one remaining aspect, and that is Typst's dynamic linking mechanism. To quote the documentation of typst_library::Routines:

Defines implementation of various Typst compiler routines as a table of function pointers.
This is essentially dynamic linking and done to allow for crate splitting.

An ingenious mechanism, if I may say so:
In a crate A, we may not refer to functions in a crate B that depends on A, but we can define some function pointers in A that we can call in A, then instantiate these function pointers with the desired functions from B in our main function.
However, the way that this is implemented in detail in Typst limits the usage of this "trick".
In particular, the function pointers in Routines are available via a field inside typst_library::Engine.
When we define a new element outside of typst-library, say in typst-libext, then we cannot use the existing dynamic linking trick to call functions on types defined in typst-libext, because that would require a function signature in typst_library::Routines that refers to a type in typst-libext, and that is impossible. For example, Routines has a function pointer layout_table that takes a TableElem, and if we move TableElem out from typst-library, we cannot refer to it in Routines anymore.

However, there is a relatively easy way out: Make an own Routines struct for typst-libext, and provide it as a global variable inside a OnceLock. This can contain functions on typst-libext types. That way, we can call layout_table from typst-libext, for example.
It might be desirable to also adopt this technique inside typst-library and to eventually remove the field to Routines from Engine, because that will allow for a further reduction of the size of typst-library.

Do you still remember my saying that we could potentially remove model::{figure, footnote} and text::raw from typst-library? Here's why I wrote "potentially": RawElem is used only in a function fn display(self) -> Content, which does not have access to Engine and thus to Routines. If we could use Routines via a global variable, we could put a function new_raw_elem inside Routines, use it in display, and then move text::raw out from typst-library. This would remove about 1000 LOC and a dependency (syntect) from typst-library, resulting in faster builds. A similar case can be made for figure and footnote. But I guess that removing Routines from Engine altogether is a somewhat political decision, and this proposal does not crucially depend on it.

Documentation

I admit that there is a potential problem that I have not researched yet, namely documentation. The documentation of Typst's standard library is generated directly from the source code, and splitting the standard library in two might complicate this somewhat. But I am confident that we could work this out.

Plan

I think that we can divide work on this into smaller PRs:

  • Add ShowPacked, FigurablePacked etc. traits into typst-library: This establishes the base on which Typst elements can be defined outside of typst-library. We could also derive these traits from their base traits automatically via a macro; I have a small prototype going already.
  • Make LibraryBuilder accept custom modules.
  • Create a new crate typst-libext containing the modules that I gave in the "Research" section. Perhaps we can even create them as symlinks to typst-library to ensure a smooth transition.
  • Adapt the documentation building process to merge stuff from typst-library and typst-libext.
  • Finally, replace the symlinks in typst-libext with the actual files from typst-library, and load the standard library from both typst-library and typst-libext in typst-cli.
  • Profit --- enjoy your reduced build times!

I'm motivated to work on all of these, in principle, but I would probably require some help with adapting the documentation building process. I'm currently completely clueless where this is done (although I searched a bit).

To summarise again the advantages:

  • Modifying any type moved to typst-libext, such as tables, bibliographies, grids, etc., will only lead to recompilation of a few crates such as typst-cli and typst-layout, whereas this currently requires recompilation of typst-{kit,realize,render,svg,pdf,layout,eval,cli}.
  • Modifying any type remaining in typst-library (such as headings) will also compile faster, because typst-library will be smaller, and the remaining parts that are in today's typst-library that have moved to typst-libext can be compiled in parallel with typst-{kit,realize,render,svg,pdf,eval}.
  • This split will make it more explicit for which types there is a "special treatment" in typst-library.

Let me know what you think about this!

Activity

  1. laurmaedje commented on Jan 7, 2025

    @laurmaedje
    Member

    In principle, I'm sympathetic to splitting up typst-library further and your ideas go into a similar direction as my previous thoughts on the matter. Just ripping out one of the top-level modules (e.g. foundations) isn't gonna work. We'd rather have to carve out pieces of them.

    My main concern with this is that we can't rip out enough to make it worth the extra complexity.1 I'm also a bit concerned about making the code base harder to navigate with two large crates that have a completely parallel structure. It's a bit of a trade-off and it very much depends on how much can actually be extracted. For what it's worth, we might also be able to extract more things over time as the code evolves (e.g. with custom types I want to get rid of enum Value which means some of the enum variants like Duration could probably move out).

    Specific comments on your design (mostly bike-shedding):

    • I would prefer the split to be typst-core / typst-library rather than typst-library / typst-libext. Most of the other crates only depend on the more foundational of types and elements (e.g. TextElem) and would thus depend on typst-core. typst-library would reexport the typst-core types and assemble the Library itself (including all the fn define functions).

    • Regarding the Packed trouble: I also ran into this problem and did find out that #[fundamental] would solve all our problems, but its unstable. However, I didn't come up with your solution. It looks quite good, though I would consider a different naming. Since Show is primarily used in its impls, maybe this would be the main trait and the object-safe variant would get a different name.

    • Regarding routines: It's a bit unfortunate to store routines in a global because it might not be populated by the time it is accessed. Meanwhile, the Engine-based approach ensures that it is available. If we don't find a better solution, perhaps it is okay, but it would a bit unfortunate.

    • Documentation: I don't think it will be a problem. When reexporting typst-core in typst-library (in the individual modules, so e.g. typst_library::layout would reexport typst_core::layout::*), the public API surface should be identical and the docs generation shouldn't need any (or at least not any big) changes.

    Footnotes

    1. I actually did experiment with such a split 9 months ago and I couldn't extract enough to make it worth it at the time. However, that was before the other crates were extracted, so things might be quite different now. ↩

  2. 01mf02 commented on Jan 7, 2025

    @01mf02
    ContributorAuthor

    For the reference: While reading a bit about #[fundamental], I found #3200, which introduces the Packed type. This PR contains an interesting quote:

    Show for Packed<T> can only be implemented in the crate where Packed is defined because of the orphan rules and the lack of #[fundamental] on stable.

  3. laurmaedje commented on Jan 7, 2025

    @laurmaedje
    Member

    I also wrote

    This means it would not be possible to implement a new element outside of the typst crate. Still, if that ability should be needed in the future, we could define a decl-macro that makes it simple to define a crate-local Packed alternative in a downstream crate and add an associated Packed type to NativeElement which specifies which Packed type an element uses. Generic uses of Packed would need to be switched to ::Packed (which could also be realized through Packed being a type alias to that).

    Which is immensely more complicated than Show/ShowPacked. It's a really nice solution compared to what I came up with so far.

    Testing it a little, I think just flipping around the naming makes perfect sense. The name ShowPacked still works well:

    • impl Show for HeadingElem
    • impl<T: Show> ShowPacked for Packed<T>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    refactor

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions