⚠ This text is draft.

apfmt: A Pretty Expressive Rust formatter

October 19, 2026

A few months ago I realized that I do not really know how code formatters work. So I read some papers. I expected a paper from the 80s with one standard approach that everybody uses with small tweaks. To my surprise, the good ideas are much younger.

I found A Pretty But Not Greedy Printer (2017) [paper]. It looks at all possible layouts at once and keeps only the useful ones (a Pareto frontier). I liked that idea fell into the rabbit hole. Just for fun, I wrote a prototype of a Rust formatter with it. While doing it, I found that translating the Rust syntax tree into its operators was a bit clumsy. Then I found A Pretty Expressive Printer (2023) [paper], which was a better fit for the job.

The result is apfmt, a Rust formatter written from scratch on these ideas. I wrote it for fun and to learn, but it works better than I expected. This post is about how it works and how it compares to rustfmt.

If you only want the comparison, jump to the comparison with rustfmt.

Split between formatting and choosing the layout

We start with simplified version in similar way as described in "A Pretty Expressive printer". In the following section, we will speak extensions introduced in real implementation of apfmt.

As descibed in both paper, apfmt formatting work is splitted into two independent parts:

  1. Formatting knows Rust. It says what layouts are possible, but it does not choose (with some exceptions where a layout can be quickly rejected on a local decision)
  2. Resolver knows nothing about Rust. It only chooses the best layout.

The trick is that we cannot do this split naively, since there are exponentially many possible formattings:

Let us first assume just a simple function call my_f(1, 2, 3) then there are two possible layouts:

Single line
my_f(1, 2, 3)
Separate lines
my_f(
  1,
  2,
  3,
)

When function calls are nested, number of combination grows exponentially. It is actually even more messier as just nested calls introduce other possible options to format:

variant 1
my_function(
    g(1, 2, 3)
)
variant 2
my_function(g(
    1, 2, 3
))

And all things get much more complicated with rules for closures, placing comments, rules for breaking expressions like vec![...] and many others. And we still are just in function calls.

The intermediate language: Doc

The glue between the formatting and resolving parts is a small language. A program in it describes a set of strings, the possible layouts of the code. It is basically a context-free grammsar. The basic operations are:

  • A text, or a new line: "abc", \n
  • Concat: join two things. (concat "ab" "cd") gives abcd
  • Alt: a choice. (alt "ab" "cd") gives two outputs "ab" and "cd.
  • Nest: indent the new lines inside. (nest (concat "ab" \n "cd")) gives "....ab\n....cd" (Char . means a space here)

A slightly more complex example has five layouts:

(alt (concat (alt "x" "y") (alt "1" "2")) "z")  =>  x1, x2, y1, y2, z

Let us demonstrate the power of this on a paragraph wrapping. This has direct connection to Rust code formatting, e.g. listings after use keyword are with some additional rules formated in this way.

In paragraph wrapping, between every two words there is a choice: a space or a new line. We will denote it as X = (alt " " \n).

(concat "aaa" X "bbb" X "ccc" X "ddd" X ...)

With n words it has 2^(n-1) layouts. But we expressing this set in a compact way. And this also gives an opportunity to implement a solver that find the best layout without looking one by one on each of them.

Let us note that Doc structure is actually a DAG, that allows to reuse a nodes that is also crutial for a compact representation:

Here is the Doc for a call f(1, 2, 3) with two possible layouts that we have seen above (flat or every arg on own line):

Note that in fact it is not a tree but a DAG (a graph without cycles): the same sub-document can be used from many alternatives, and it is only stored once. This is how a small structure describes exponentially many layouts.

The solver

The resolver walks the DAG from the leaves up. For each node, it computes the set of useful layouts of this node, not all of them. For purpose of comparison we reduce each layout to 3 numbers:

  • Baddess - How much the layout overflows the page.
  • Height - The number of lines of the layout.
  • Length of the last line - The number of characters at the last line.

Now we can establish a partial ordering over 2D space:

  • First dimension is cost that is an lexicographically ordered tuple (Baddess, Height); overflow is always worse than any number of lines.
  • Second dimension is last line length; smaller value means that more code may follow on the same line after concatenation.

If layout A is not worse than layout B in both ways, B can be thrown away, because whatever follows, A is at least as good. This establish Pareto frontier: layouts where a better cost means a wider last line.

The size of frontier is (roughly) bounded by about number of maximal columns, since it bounds length of last line and there is at most one cost for each length of the last line. In my experiments on a corpus of well-known crates, the size of the frontier never goes over 10.

Technical side note: The fact that fontier is small follows from the fact that is it is 2D frontier. For 3D frontier it would be not that easy. And the is also one differences between approaches from A Pretty But Not Greedy Printer and A Pretty Expressive Printer. In the first paper, the frontier is 3D and it may cause performance problems. The pretty expressive printer, when we are going down the Doc DAG, we are evaluating layouts in the context of the current column. In the "not greedy printer" layouts are evaluated without context; that on one hand allows for a simpler caching, but it also needs an extra dimension in the frontier.

The example of solver

Let us return to the text wrapping example and assume that max width is set to 8. For clarity, I will denote space as _ and a newline as ⏎ in the tables.

(concat "aaa" X "bbb" X "ccc") where X = (alt " " \n)

"aaa" at column 0 is evaluated just to "aaa" with the following metrics:

LayoutOverflowLinesLast line
aaa013

Then evaluating X at to column 3 gives us:

LayoutOverflowLinesLast line
_014
⏎020

If we compare costs and last line of each solution, they are incomparable bot lays on pareto frontier: cost (0, 1) and last line 4 vs cost (0, 2) and last line 0.

If we concat these two layout sets we get:

LayoutOverflowLinesLast line
aaa_014
aaa⏎020

By evaluating "bbb", concat, and X (in different column than previously) we get into:

LayoutOverflowLinesLast lineKept
aaa_bbb_018✅
aaa_bbb⏎020✅
aaa⏎bbb_024❌
aaa⏎bbb⏎030❌

Here we can safely remove 3rd and 4th row, because it is dominated by the second column. The cost (0, 2) with last line 0 is better than what can last two rows offer.

Now if we cancat to the first two rows evaluated "ccc" we get the following layouts:

LayoutOverflowLinesLast line
aaa_bbb_ccc2110
aaa_bbb⏎ccc020

This operation introduces overflow in the first solution, but since they are still incomparable so we will keep it. If this is the whole document and resulting set of layouts. We choose final layout by the cost, so the second row is the final layout.

Beyound the paper

The Pretty Expressive Printer is small and clean idea but we need some more ingredients to build a full featured Rust formatter.

The first thing we need to get a syntax tree, at I have chosen the syntax tree from Rust analyzer, it has adventage (compared to rustc parser) of fully keeping comments in the code (even with that it was a big pain in the actual implementation as we will se below).

Another thing is normalization. The simple normalization as adding/removing trailing spaces can be confortably expressed by introduced "pretty expressive" machinery. But for more complex normalizations like alphabetical sorting of use declarations we need a separate step. For the sake of simplicity it is done in the separated step. The intermediate product is again full source code that is reparsed.

I have also added more Doc nodes and more complex cost expressions that finally looks like:

  1. Badness - sum of overflows.
  2. Line costs - generalized cost where the currency are lines; each line add +1 to cost. Some operation may also modify this costs so it may express some preferences and dispreferences in exchange of more lines e.g. a penalty for splitting a thing that the Style Guide wants on one line, like a generics clause.
  3. weak preference - decides between layouts that are equal in everything else. Used for finetuning layouts preference.

In the original paper, the authors adds the square root of overflow into the badness. It did not worked for me as squering of large overflow generate large values and formatter is then willing to accept many smaller overflows just to slightly reduce one big overflow that is usually unavoidable.

Also the original paper add custom penalties into badness. I am switch it to two separated costs where the stronger one also accounts number of length. It has following adventages:

  • Overflows are inherently bad, no custom preferences cannot override it.
  • Strong custom preference has explcit currency. You are excahnges number of lines wrt. some preference layouts. (e.g. you are saying that you are dispreffering this as long as it does not save more than two lines)
  • Weak prerefence allows express small finetuning without rist of interfering with main preferences and we can get rid of some constants fine tuning.

Note that we are still maitinging 2D frontier as all these costs still represents one dimension, we are just linearly ordering a bigger tuple.

Doc langauge was also introduces a new kind of operations for transformation of Rust syntax rules into Doc.

Filters:

  • Flat - keeps only layouts that takes only a single line
  • MultiLine - keeps only layouts that takes more then one line.
  • ShortLastLine - keeps layouts whose last line ends at most at the indentation of a nested line.
  • RoomAfter(n) - keeps only layouts whose last line ends at least n columns before the page width.
  • FirstLineWithin(n) - keeps only layouts whose first line spans at most n columns from the start

Modificators for costs:

  • LineCost(c) - unconditional modification of line cost
  • WeakPreference(p) - unditional modification of weak preference
  • KeepTogeher(c) - layouts spanning over multiple lines get const c into line cost. Cost is added just once, not per line.

Others:

  • IgnoreOverflow - Resets overflow (used for trailing comments, so code is not penalized for a long trailing comment)
  • AlignMark - It does not have immediate effect on layout but inserts a mark that is used for aligning trailing comments in the postprocessing phase (see the paragraph below).
  • Fallback - Has two childs as Alt but when first child produce at least one layout then the second child is ignored.

After the resolver there is one extra step and it is resolving trailing comment aligning. Example:

const COLORS: [(&str, u32); 4] = [
    ("red", 0xff0000),             // primary
    ("green", 0x00ff00),           // primary
    ("cornflower_blue", 0x6495ed), // named
    ("x", 0),                      // placeholder
];

This is part is not resolved in the previous steps as it would be complicated and indentation of trailing comments. As they cannot change layout so I am ofloading to the separate phase. The resolver only contains operation that marks the position that should be aligned together with some extra functionality (see below).

Comparison with rustfmt

100% compatability with rustfmt is not a goal. apfmt was created under these principles:

  • apfmt follows Rust Style Guide with a few exceptions.
  • apfmt is quite compatible with rustfmt, but 100% compatibility is a non-goal. If apfmt and rustfmt differ:
    • If the apfmt output is better, the difference is desired.
    • If both results are equally good and it is cheap to be compatible with rustfmt, it is a bug.
    • If both results are equally good and being compatible is expensive, it will be kept as it is.
    • If the apfmt output is worse, it is a bug.

The diferences between rustfmt and apfmt are listed here.

Notable output differences

Utilization of pareto frontier

rustfmt decides many things with local rules, without seeing how the rest of the statement turns out. A good example is the right side of =: rustfmt moves it to the next line when its first line on the line of = ends with (, { or [ and on the next line it does not. Here, that decision means the chain no longer fits on one line, so it is broken before every element:

apfmt
req.data = self.handle_data.request_callbacks.borrow_mut().insert(
    RequestCallbackState::Write(WriteRequestCallbackState {
        isolate: unsafe { scope.as_raw_isolate_ptr() },
        req_wrap_obj: v8::Global::new(scope, req_wrap_obj),
        stream_handle,
    }),
);
rustfmt
req.data =
    self.handle_data
        .request_callbacks
        .borrow_mut()
        .insert(RequestCallbackState::Write(WriteRequestCallbackState {
            isolate: unsafe { scope.as_raw_isolate_ptr() },
            req_wrap_obj: v8::Global::new(scope, req_wrap_obj),
            stream_handle,
        }));

apfmt has no such rule. Both layouts are in the Doc, both survive in the frontier until the whole statement is known, and the resolver then simply picks the one with fewer lines (7 instead of 9).

Comments

Comments are much bigger pain that I would ever imaged. They could be practically everywhere, between every two tokens, two follwing comments, etc. Many situations where it is very unclear how should formatting look like. In many cases it also depends on the text inside, what the comment is actually about and how they connect to surrding code. Total headache.

So I would understand that formatting of comments are sometimes weird, but rustfmt in many positions just silently drops comments , e.g. around ->, inside parenthesized types or inside use declarations. In the case of use a::{ /* only */ };, it drops the whole declaration. apfmt keeps every comment as far as I know, even it costs a lot of complexities in the transforming code from syntax tree to Doc.

Input
fn around_arrow() /* a */ -> /* b */ u32 {}
type T = &(
    // c
    dyn A
);
use a::d as /* r */ e;
use a::{/* empty */};
apfmt
fn around_arrow() /* a */ -> /* b */ u32 {}
type T = &(
    // c
    dyn A
);
use a::d as /* r */ e;
use a::{/* empty */};
rustfmt
fn around_arrow() -> u32 {}
type T = &(dyn A);
use a::d as e;

When a multi-line block comment moves, apfmt keeps the columns of its lines relative to its start, so aligned text keeps its shape. rustfmt reindents every line to the indentation of the code:

Input
fn f() {
    let x = 10;   /* a
                      a
                       a */
}
apfmt
fn f() {
    let x = 10; /* a
                    a
                     a */
}
rustfmt
fn f() {
    let x = 10; /* a
    a
    a */
}

I have addad some more improvements wrt comments. Both formatters align trailing comments, but rustfmt aligns them to the widest item, however far right that pushes the comments. apfmt leaves out a few items that are much wider than the rest (more than 40 columns by default, configurable by trailing_comment_align_threshold):

apfmt
enum E {
    A = 1,  // a
    Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb = 2, // b
    Cc = 3, // c
    D = 4,  // d
}
apfmt
enum E {
    A = 1,                                                                 // a
    Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb = 2, // b
    Cc = 3,                                                                // c
    D = 4,                                                                 // d
}

Do not give up

When rustfmt cannot find a layout that it likes, it often gives up and copies the code as written, including its indentation and spacing, without saying a word. A typical trigger is a comment in an unusual place (look at line with compute):

apfmt
fn f() {
    let x =
        // c
        compute(a, b);
}
rustfmt
fn f() {
    let x =
      // c
      compute(  a,b );
}

apfmt tries harder and not gives up on more places than rustfmt. Morever whenever it happends it is always reported.

Regularity

A single call argument that can be broken and that is wider than fn_call_width is never kept on one line in the call. rustfmt keeps the call on one line when the first line of the hugged argument does not fit fn_call_width but the whole call fits max_width. So a longer name can take fewer lines than a shorter one. In apfmt, a longer argument never takes fewer lines than a shorter one:

apfmt
outer(pppppppppppppppppppppppppppppppppppppppp::new(b, c));
outer(pppppppppppppppppppppppppppppppppppppppppppppppppppp::new(
    b, c,
));
outer(
    pppppppppppppppppppppppppppppppppppppppppppppppppppppppp::new(b, c),
);
outer(
    pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp::new(b, c),
);
rustfmt
outer(pppppppppppppppppppppppppppppppppppppppp::new(b, c));
outer(pppppppppppppppppppppppppppppppppppppppppppppppppppp::new(
    b, c,
));
outer(pppppppppppppppppppppppppppppppppppppppppppppppppppppppp::new(b, c));
outer(pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp::new(b, c));

A line that cannot fit (e.g. a long string literal) is just one overflowing line for apfmt, and the code around it is formatted as usual. In rustfmt, one such line often makes the whole expression unformatted:

apfmt
let w = xs
    .iter()
    .map(|c| {
        let s =
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        s
    })
    .collect::<Vec<_>>();
rustfmt
let w = xs.iter().map(|c| {
    let s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    s
}).collect::<Vec<_>>();

Some arbitrary choices

Some differences are just choices where neither side is clearly right. When the only argument of a call does not fit on the line of the call, rustfmt hugs it (outer(inner( ... ))) and breaks its contents. apfmt puts the argument on its own line if it fits there, which takes fewer lines:

apfmt
outer(
    inner(first_argument_value, second_argument_value, third_xxx),
);
rustfmt
outer(inner(
    first_argument_value,
    second_argument_value,
    third_xxx,
));

Performance

Real code

The whole approach is quite comparable with rustfmt. On raw formatting one file at time is apfmt even better (1.0 = rustfmt, lower is better)

I measured eight well-known crates on a 16-core machine (rustfmt 1.11.0, best of three runs). "Per file" runs one process per .rs file through stdin, so it includes process startup. The other columns format the whole package at once: cargo fmt runs one rustfmt process, cargo apfmt runs in one process on all threads, or on one thread with -j1. The numbers in parentheses are relative to rustfmt (lower is better).

ProjectFilesLinesPer file: rustfmtPer file: apfmtcargo fmtcargo apfmt -j1cargo apfmt
tokio814189,5047.22 s2.15 s (0.30)0.31 s0.75 s (2.43)0.10 s (0.31)
serde20842,6271.87 s0.53 s (0.28)0.16 s0.21 s (1.26)0.05 s (0.31)
clap33784,6683.08 s1.01 s (0.33)0.23 s0.38 s (1.66)0.06 s (0.27)
regex227160,9862.34 s1.37 s (0.58)0.48 s1.02 s (2.11)0.13 s (0.27)
ripgrep10255,3241.05 s0.62 s (0.59)0.21 s0.48 s (2.26)0.09 s (0.44)
axum30247,6352.72 s0.77 s (0.28)0.18 s0.36 s (2.00)0.06 s (0.36)
hyper10035,8290.99 s0.46 s (0.46)0.16 s0.22 s (1.42)0.08 s (0.50)
syn13371,0261.40 s0.87 s (0.62)0.20 s0.61 s (3.00)0.10 s (0.50)

To be fair, the per-file advantage comes largely from the cheaper startup of apfmt. On one thread, apfmt is 1.3–3× slower than rustfmt on the actual formatting. Exploring alternatives has its price. But the work splits naturally by files, so with all threads cargo apfmt is 2–4× faster than cargo fmt. A single apfmt process stays at 13–30 MB of peak memory, compared with about 40 MB for rustfmt.

Adversary code

The interesting question for a printer that explores alternatives is the worst case. As an adversary I used closures nested as the only arguments of method calls, x.all(|a| x.all(|a| x.all(|a| x))), with depth n. Each level offers several layouts that contain the inner closure.

Depth10131415203060100
rustfmt0.59 s12.0 s33.9 s101 s––––
apfmt0.008 s0.014 s0.017 s0.019 s0.08 s0.18 s1.45 s8.26 s

rustfmt is exponential here: every extra level makes it roughly three times slower, and I stopped measuring after depth 15. apfmt grows polynomially, thanks to the memoization of the layouts of Alt nodes by their column. Depth 100 takes under 9 seconds. (When the innermost body is a block, { x; y }, rustfmt is slightly slower and apfmt about 4× faster.) Of course nobody writes code like this, but it shows that the cost of exploring alternatives is under control.

Conclusion

Co nebylo doruceno: custom parsovani maker