Skip to content
Closed
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
126d731
Bun.Transpiler: add unstable_parse() to expose the internal AST
robobun Aug 1, 2026
d75933f
reword \u escape comments to avoid diff-hygiene grep
robobun Aug 1, 2026
08a16c6
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 1, 2026
af8c964
trim comments per comment-cop review
robobun Aug 1, 2026
89d440b
trim remaining doc comments to two lines
robobun Aug 1, 2026
3b6c16f
collapse remaining doc comments to single lines
robobun Aug 1, 2026
13f5721
address review: rename property/import 'kind' to avoid node contract …
robobun Aug 1, 2026
bd44a0b
docs: list approximateNewlineCount among top-level unstable_parse fields
robobun Aug 1, 2026
db81afb
str(): match decode_wtf8_one on malformed UTF-8 (pass unclamped width…
robobun Aug 1, 2026
607d4ee
ci: retrigger
robobun Aug 1, 2026
395f009
unstable_parse: add {format:'raw'} mode (self-describing binary tape …
robobun Aug 2, 2026
775695d
trim multi-line comments per comment-cop
robobun Aug 2, 2026
b71ab70
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 2, 2026
c35e75d
raw mode: address review (cache key, visitNode kind check, key_id ass…
robobun Aug 2, 2026
ba9434d
raw mode: guard u32 tape-offset overflow; tighten test assertions
robobun Aug 2, 2026
fea4250
drop accidentally-committed files; shorten overflow doc comment
robobun Aug 2, 2026
7ee5175
raw mode: preserve lone surrogates via TY_STR16
robobun Aug 2, 2026
7295d06
fix empty-string pool collision, UAF via options getter, and BOM stri…
robobun Aug 2, 2026
175cb1d
drop unrelated files that keep getting re-staged
robobun Aug 2, 2026
affcc92
readString16: chunk String.fromCharCode.apply to avoid arg-count Rang…
robobun Aug 2, 2026
a3e72b6
str(): use WHATWG maximal-subpart on decode failure so FFFD count mat…
robobun Aug 2, 2026
7a38bdb
shorten utf8_maximal_subpart doc comment per comment-cop
robobun Aug 2, 2026
31daac7
str(): reject WTF-8-encoded surrogates to match TextDecoder
robobun Aug 2, 2026
025a590
unstable_parse: drop object mode; always return {buffer, root, visit}
robobun Aug 3, 2026
d5c4725
shorten file doc comment per comment-cop
robobun Aug 3, 2026
7aedaf6
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 3, 2026
5016e70
node proxy: fall through to Reflect.get; f_f64: preserve -0 sign
robobun Aug 3, 2026
35116cb
nodeHandler.has: fall through to Reflect.has to match get trap
robobun Aug 3, 2026
c0c10c4
drop unrelated README that leaked into the previous commit
robobun Aug 3, 2026
c8dead8
visit(): only dispatch enter on kind-bearing nodes
robobun Aug 3, 2026
2a7122e
drop tamper-able instanceof ArrayBuffer guard
robobun Aug 3, 2026
809cf60
ast_to_tape: clamp pre-sizing reserve hint to 16 MiB
robobun Aug 3, 2026
221a162
unstable_parse: strongly-typed visitor keys and thorough JSDoc
robobun Aug 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions docs/runtime/transpiler.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,60 @@ const result = transpiler.scanImports(code);

</CodeGroup>

## `.unstable_parse()`

<Warning>
**Unstable.** This method exposes Bun's internal AST. The output is **not** ESTree-compatible and the shape (node
kinds, field names, nesting) may change or be removed in any patch release without a deprecation period. Use it for
experimentation and tooling you control end to end.
</Warning>

Parse code and return the AST as `{ buffer, root, visit }`. The AST is written
to a compact binary tape in `buffer`; `root` is a lazy proxy that decodes
fields on access, and `visit()` walks every node by `kind`. Every node has a
`kind` (a snake_case tag like `"s_local"`, `"e_binary"`, `"b_identifier"`) and
a `loc` (byte offset into the input, or `null`). `JSON.stringify(root)`
materializes the full tree.

```ts example.ts icon="/icons/typescript.svg"
const t = new Bun.Transpiler({ loader: "ts" });
const { root, visit } = t.unstable_parse(`export const x: number = 1 + 2;`);

root.stmts[0].decls[0].value.op;
// "bin_add"

JSON.parse(JSON.stringify(root.stmts[0]));
// {
// kind: "s_local",
// loc: 7,
// declKind: "k_const",
// isExport: true,
// decls: [
// {
// binding: { kind: "b_identifier", loc: 13, name: "x" },
// value: {
// kind: "e_binary", loc: 25, op: "bin_add",
// left: { kind: "e_number", loc: 25, value: 1 },
// right: { kind: "e_number", loc: 29, value: 2 },
// },
// },
// ],
// }

visit({
e_binary(n) {
console.log(n.op);
},
s_function() {
return false;
}, // skip subtree
});
```

`root` carries `stmts`, `symbols`, `importRecords`, `hashbang`, `directive`,
`exportsKind`, and `approximateNewlineCount`. Identifier nodes resolve their
`Ref` to the symbol's original name string.

---

## Reference
Expand Down Expand Up @@ -248,6 +302,13 @@ class Bun.Transpiler {

scan(code: string): {exports: string[], imports: Import}
scanImports(code: string): Import[]

/** Unstable: returns Bun's internal AST. Shape may change any release. */
unstable_parse(code: string, loader?: Loader): {
buffer: ArrayBuffer;
root: UnstableAST;
visit: (visitors: Record<string, (n: UnstableASTNode) => boolean | void>) => void;
}
}

type Import = {
Expand Down
88 changes: 88 additions & 0 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2600,6 +2600,94 @@ declare module "bun" {
* This is a fast path which performs less work than `scan`.
*/
scanImports(code: Bun.StringOrBuffer): Import[];

/**
* Parse code and return Bun's internal AST as a plain JavaScript object.
*
* **Unstable.** The returned shape is Bun's internal AST, not ESTree. Node
* kinds, field names, and structure may change or be removed in any patch
* release without notice. Use this for experimentation and tooling you
* control, not for published packages that need forward compatibility.
*
* The AST is written to a compact binary tape in `buffer`; `root` is a lazy
* proxy over it that decodes fields on access, so large files don't pay the
* full materialization cost up front. `JSON.stringify(root)` materializes
* the whole tree. Every node has at least:
* - `kind`: a snake_case tag string (e.g. `"s_local"`, `"e_binary"`, `"b_identifier"`)
* - `loc`: byte offset into the source, or `null`
*
* @param code The code to parse
* @param loader Override the loader for this call (defaults to the constructor's `loader`)
* @experimental
* @example
* ```ts
* const t = new Bun.Transpiler({ loader: "ts" });
* const { root, visit } = t.unstable_parse(`const x: number = 1 + 2;`);
* root.stmts[0].decls[0].value.op; // "bin_add"
* visit({ e_call(n) { console.log(n.target.name) } });
* ```
*/
unstable_parse(
code: Bun.StringOrBuffer,
loader?: JavaScriptLoader | { loader?: JavaScriptLoader },
): UnstableParseResult;
}

/**
* The return value of {@link Transpiler.unstable_parse}.
*
* **Unstable.** Both the node shapes and the buffer encoding may change in
* any patch release.
* @experimental
*/
interface UnstableParseResult {
/** The self-describing binary tape. `root` and `visit` read from this. */
buffer: ArrayBuffer;
/** Lazy proxy over the tape; `JSON.stringify(root)` materializes the full tree. */
root: UnstableAST;
/** Walk every node under `root.stmts`, dispatching on `kind`; a handler returning `false` skips its subtree. */
visit: (
visitors: { enter?: (node: UnstableASTNode) => boolean | void } & Record<
string,
(node: UnstableASTNode) => boolean | void
>,
) => void;
Comment thread
robobun marked this conversation as resolved.
Resolved
}

/**
* The root AST node from {@link Transpiler.unstable_parse}.
*
* **Unstable.** This type is intentionally loose: the node shapes are Bun's
* internal AST and may change between patch releases.
* @experimental
*/
interface UnstableAST {
kind: "ast";
/** `#!` line without the trailing newline, or `null`. */
hashbang: string | null;
/** The top-level directive prologue (e.g. `"use strict"`), or `null`. */
directive: string | null;
exportsKind: string;
approximateNewlineCount: number;
importRecords: { path: string; kind: ImportKind }[];
/** Every symbol the parser created, in declaration order. */
symbols: { name: string; kind: string }[];
/** Top-level statements. */
stmts: UnstableASTNode[];
}

/**
* An AST node from {@link Transpiler.unstable_parse}. Only `kind` and `loc`
* are stable; all other fields are node-specific and may change between
* patch releases.
* @experimental
*/
interface UnstableASTNode {
/** Snake_case discriminant, e.g. `"s_local"`, `"e_call"`, `"b_identifier"`. */
kind: string;
/** Byte offset into the input, or `null` for synthetic nodes. */
loc: number | null;
[field: string]: unknown;
}

type ImportKind =
Expand Down
1 change: 1 addition & 0 deletions src/js/builtins/BunBuiltinNames.h
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ using namespace JSC;
macro(toNamespacedPath) \
macro(transform) \
macro(type) \
macro(unstableParseNative) \
macro(updateRef) \
macro(url) \
macro(validated) \
Expand Down
Loading
Loading