Get more of your program typed

How to read bun compile --explain, and what to change for each cause it reports

Ahead-of-time compilation is experimental.

bun compile --explain lists the lines that slow your compiled code down, with a fix for each. The line whose change alone speeds up the most operations in loops comes first. Fix the first entry and run it again. Stop when the entries that are left aren't in hot code.

bun check --aot --explain prints the same report without building.

Read an entry#

main.ts
interface Item {
  sku: string;
  price: number;
}

const items: Item[] = [{ sku: "A-1", price: 2.5 }];
const saved: any = JSON.parse('{ "sku": "B-2", "price": 10 }');
items.push(saved);

let total = 0;
for (const item of items) total += item.price;
console.log(total);
terminal
bun compile ./main.ts --explain
7 | const saved: any = JSON.parse('{ "sku": "B-2", "price": 10 }');
                            ^
note: 1. unknown-object: The compiler doesn't know the shape of what JSON.parse() returns.
   at main.ts:7:25

note: 1 of 1 untyped access
note: 1 of these runs in a loop
note: used at main.ts:11:36
note: fix: check its fields and build a new object from them.
note: https://bun.com/docs/compiler/explain#unknown-object
LineWhat it tells you
1. unknown-objectThe rank, the cause and why
atThe line to change, where the compiler lost track of the type
1 of 1 untyped accessHow many of your untyped accesses this line causes
1 untyped operatorOperators on a value of unknown type
1 indirect callCalls where the callee isn't known
1 of these runs in a loopHow many are in loops
1 of these has another cause tooThese get faster when the other cause is fixed as well
it comes in atWhere the value gets between objects, if that's another line
used atThe lines that run slower
fix:What to change

The compiler follows each value back to where its type was lost, through variables, fields, arrays, parameters and results. Here that's the result of JSON.parse, and the line that runs slower is the read of item.price four lines below it. Where there's no such line, the entry has the location of the operation itself.

The first entry is the line whose change alone speeds up the most operations in loops, then come the ones with the most operations elsewhere. Entries with nothing to change in your types come last. Nothing is measured.

The report shows the first 20 entries. --explain=json prints all of them.

In --explain=json, why says what happened at the line, and uses lists the lines that run slower:

whyAt the line
builtin-result, call-result, property-readA value of unknown shape comes from this call or read
outside-callerCode that the compiler can't see gets a function that it can call with any values
exposed-object, exposed-variableCode that the compiler can't see gets an object or a variable that it can change
caught-exceptionA catch gets any value
other-value, other-builtin, other-functionSomething else gets to a place that holds objects
array-argumentThe argument of new Array() may not be a number, so it may become an element
many-shapes, many-functionsToo many shapes or functions come together
changed-shapeA property is added, deleted or redefined
missing-field, checked-elementThe compiler can't prove that the field or the element exists
checked-result, checked-keysA result, or the properties of a copied object, are checked
builtin-property, computed-nameThe property is looked up by name
static-fieldA static field is added to its class, once

What is counted#

The report ends with the share of your property accesses that are typed. Code in node_modules gets a line of its own.

Dependencies: 3.1% of property accesses are one load: 210 free, 1,320 tested, 5,244 by name (6,774)
92.4% of property accesses are one load: 1,204 free, 61 tested, 38 by name (1,303)
WordThe compiled code
freeOne load or store at a fixed offset
testedA check each time, such as of the shape, then the load or store
by nameA lookup at run time

Only the code that usually runs counts. When the lookup is the failing side of a check, the access is tested. When the check runs once before a loop, the accesses in the loop are free.

Only free counts as typed. An access is free when the compiler knows every shape the object can have at that point, from your types or by tracking the object from where it's created. An any or a .js file doesn't break that by itself.

A property access is a read, a write, an in test or a delete. Reads and writes of array elements count too, Map operations don't. Properties of objects that Bun gives you, such as req.params.id or process.env.PORT, are always lookups. So a small server has a low percentage, which doesn't matter outside of hot code.

Bun counts after optimization, so the total moves when you change code nearby.

Other reports#

FlagLists
--explain=jsonEvery entry, one JSON object per line
--explain=guardsType guards that can fail at run time
--explain=guards-jsonThe same guards, one JSON object per line
--explain=trimWhat --trim kept, and why
--explain=allocationsWhere objects are allocated

You can pass --explain more than once. In Bun.build, compile: { aotExplain: ["guards"] } adds the lines to result.logs.

Causes#

The first line of an entry has one of these codes.

unknown-object#

The compiler doesn't know the shape of an object, so accesses to it are lookups or need a check. Without a reason of its own, the entry has the location of the access.

The objectWhat to do
Comes from JSON.parse, response.json(), eval or a module loaded at run timeCheck its fields and build a new object from them
Comes from Bun or Node.js, like process.env or fs.statSync()Read what you need outside your loops
Is an instance of a class that extends Array, Error or another built-inFine for errors. Otherwise hold the built-in object in a field
It or another instance of its class is passed to Object.assign, Object.defineProperty or Object.createAssign the fields yourself, declare them in the class, or use extends
Is an array, a string or a function that's used as an object type, like { length: number }Pass an object literal or a class instance

To build a new object, take the value as unknown and check each field.

function readItem(value: unknown): Item {
  if (typeof value !== "object" || value === null) throw new Error("item: not an object");
  const { sku, price } = value as Record<string, unknown>;
  if (typeof sku !== "string") throw new Error("item: sku must be a string");
  if (typeof price !== "number") throw new Error("item: price must be a number");
  return { sku, price };
}

items.push(saved); 
items.push(readItem(saved)); 

The reads inside readItem are still lookups, but they run once per item and not in your loops.

unknown-callee#

The compiler can't tell which function a call reaches, as in handlers[name](request) or a method of an unknown object. The call is indirect and its result has no type. Call the function directly. If you can't, narrow the result so that the code after it is typed.

unknown#

The compiler recorded no reason. That's a bug in Bun. Report it with the entry.

lost-track#

An operator such as +, < or === runs on a value whose type the compiler doesn't know. The entry goes away when the type of the value is known, for example with typeof.