# Yuku, a JavaScript/TypeScript Compiler Toolchain in Zig > Yuku is a JavaScript and TypeScript compiler toolchain written in Zig. > Full documentation, every page concatenated for LLMs. Index: https://yuku.fyi/llms.txt # Introduction Source: https://yuku.fyi/ Yuku is a high-performance JavaScript/TypeScript compiler toolchain written in Zig. It is designed for correctness, performance, and clarity. [Try it in the playground →](https://playground.yuku.fyi) ## Why Yuku **Correct.** Yuku is 100% ECMAScript spec compliant. Zero failures and zero AST mismatches. Read [how Yuku is tested](https://yuku.fyi/testing/). **Fast.** Built using data-oriented design principles and generous performance engineering, see [Performance](#performance). **Anywhere.** Node.js, Bun, Deno, browsers, edge runtimes, and native Zig. **Zero dependencies.** Pure Zig, with no third-party dependencies in the build or on npm. **Modern.** New and proposed syntax, including decorators, source phase and deferred imports, and `using` declarations. ## JavaScript The [JavaScript guide](https://yuku.fyi/javascript/) documents it. ## Zig These pages document it: the [parser](https://yuku.fyi/parser/), the [AST](https://yuku.fyi/parser/ast/), [semantic analysis](https://yuku.fyi/parser/semantic/), [traversal](https://yuku.fyi/parser/traverse/), and [codegen](https://yuku.fyi/parser/codegen/). ## Performance Measured on an Apple M3, with every tool doing the same work. ### Parser Natively, Yuku parses faster than Oxc and SWC. ![Parsing `typescript.js` (7.8 MB) natively · [benchmark](https://github.com/yuku-toolchain/ecmascript-parser-benchmark-native)](https://raw.githubusercontent.com/yuku-toolchain/ecmascript-parser-benchmark-native/refs/heads/main/charts/typescript.svg "Native benchmark comparing Yuku, Oxc, and SWC parsing typescript.js") On npm, it parses faster than the alternatives, on small and large files. ![Parsing `react.js` (70 KB) on npm · [benchmark](https://github.com/yuku-toolchain/ecmascript-parser-benchmark-js)](https://raw.githubusercontent.com/yuku-toolchain/ecmascript-parser-benchmark-js/refs/heads/main/charts/react.svg "npm benchmark comparing Yuku, Oxc, SWC, Babel, and Acorn parsing react.js") ![Parsing `typescript.js` (7.8 MB) on npm · [benchmark](https://github.com/yuku-toolchain/ecmascript-parser-benchmark-js)](https://raw.githubusercontent.com/yuku-toolchain/ecmascript-parser-benchmark-js/refs/heads/main/charts/typescript.svg "npm benchmark comparing Yuku, Oxc, SWC, Babel, and Acorn parsing typescript.js") ### Analyzer Analyzing a whole codebase, resolving every reference and linking every import across files, Yuku is faster than typescript-eslint and the TypeScript API, and on a single large file too. ![Analyzing three.js (755 files) on npm · [benchmark](https://github.com/yuku-toolchain/ecmascript-analyzer-benchmark-js)](https://raw.githubusercontent.com/yuku-toolchain/ecmascript-analyzer-benchmark-js/refs/heads/main/charts/three.svg "npm benchmark comparing Yuku, TypeScript, and typescript-eslint analyzing three.js") ![Analyzing `typescript.js` (7.8 MB) on npm · [benchmark](https://github.com/yuku-toolchain/ecmascript-analyzer-benchmark-js)](https://raw.githubusercontent.com/yuku-toolchain/ecmascript-analyzer-benchmark-js/refs/heads/main/charts/typescript_js.svg "npm benchmark comparing Yuku, TypeScript, and typescript-eslint analyzing typescript.js") # JavaScript Source: https://yuku.fyi/javascript/ The `yuku` package parses, analyzes, walks, builds, and prints JavaScript and TypeScript, with no third-party dependencies. It runs natively where its addon for the platform installs, and as WebAssembly everywhere else. ```bash npm install yuku ``` Cloudflare Workers and Vercel Edge run WebAssembly only from a file, so there also install `@yuku-toolchain/wasm`. ```js import { b, parse, print, walk } from "yuku"; const file = parse(` const RATE = 0.2; export const tax = (price: number) => price * RATE; export const scale = (RATE: number) => RATE * 2; `, { path: "tax.ts", analyze: true }); const rate = file.rootScope.find("RATE"); walk(file.program, { Identifier(node, ctx) { if (file.referenceOf(node)?.binding === rate) ctx.replace(b.Literal({ value: 0.2 })); }, }); print(file, { strip: true }).code; // const RATE = 0.2; // export const tax = (price) => price * 0.2; // export const scale = (RATE) => RATE * 2; ``` # Parse Source: https://yuku.fyi/javascript/parse/ `parse` reads JavaScript, TypeScript, or JSX, from a string or UTF-8 bytes, into a `SourceFile`. From Zig, see the [parser](https://yuku.fyi/parser/). ```js import { parse } from "yuku"; const file = parse(source, { path: "src/app.tsx" }); file.program; // the ESTree / TypeScript-ESTree Program file.comments; // every comment, in source order file.diagnostics; file.source; file.path; file.lang; // "tsx", from the path file.sourceType; // "module" ``` The parser recovers from errors, so a file with diagnostics still has a program. ## Options | Option | Default | Description | | ---------------- | --------------------------------------------------- | --------------------------------------------------------------------- | | `path` | none | Names the file, and sets `lang` and `sourceType` | | `lang` | from `path`, else `"js"` | `"js"`, `"jsx"`, `"ts"`, `"tsx"`, or `"dts"` | | `sourceType` | `"commonjs"` for `.cjs` and `.cts`, else `"module"` | `"module"`, `"script"`, or `"commonjs"` | | `preserveParens` | `true` | Keep `ParenthesizedExpression` nodes | | `attachComments` | `false` | Attach each comment to its node, see [Comments](#comments) | | `tokens` | `false` | Collect `file.tokens` | | `analyze` | `false` | Build the [semantic model](https://yuku.fyi/javascript/semantic/) | | `semanticErrors` | `false` | Also report the early errors that need scopes, such as redeclarations | A file holds what it was parsed with, so reading `file.tokens` or the model of a file parsed without them throws, until [`reanalyze()`](https://yuku.fyi/javascript/semantic/#after-edits) builds the model. ## Diagnostics Every part of Yuku reports problems in the code in one shape, and throws only when called wrongly. ```ts interface Diagnostic { severity: "error" | "warning" | "hint" | "info"; message: string; path: string | null; start: number; // UTF-16 offsets, like nodes end: number; labels: { start: number; end: number; message: string }[]; help: string | null; } ``` ```js for (const { start, message } of file.diagnostics) { const { line, column } = file.locate(start); console.log(`${file.path}:${line}:${column + 1} ${message}`); } ``` ## Comments `file.comments` lists every comment as `{ type, value, start, end }`. With `attachComments: true`, each also belongs to the node it prints with. ```js const { program } = parse(`// header\nfunction foo() {} // trailing`, { attachComments: true }); program.body[0].comments; // [ // { type: "Line", value: " header", start: 0, end: 9, position: "before", sameLine: false }, // { type: "Line", value: " trailing", start: 28, end: 39, position: "after", sameLine: true }, // ] ``` [`print`](https://yuku.fyi/javascript/print/) prints from `node.comments`, so comments move with their nodes. ## Tokens `file.tokens` is a `TokenList`, where a token is an index. ```js import { parse, TokenKind } from "yuku"; const { tokens } = parse(source, { tokens: true }); for (let i = 0; i < tokens.length; i++) { if (tokens.kind(i) === TokenKind.Arrow) console.log(tokens.start(i), tokens.text(i)); } ``` ```js tokens.kind(i) // one of TokenKind tokens.text(i) tokens.start(i) // UTF-16 offsets tokens.end(i) tokens.isKeyword(i) tokens.isReserved(i) tokens.isUnconditionallyReserved(i) tokens.isStrictModeReserved(i) tokens.isIdentifierLike(i) tokens.isNumericLiteral(i) tokens.isBinaryOperator(i) tokens.isLogicalOperator(i) tokens.isUnaryOperator(i) tokens.isAssignmentOperator(i) tokens.precedence(i) tokens.newlineBefore(i) tokens.escaped(i) tokens.invalidEscape(i) tokens.loneSurrogate(i) tokens.range(node) // from, to) of the tokens inside a node tokens.before(offset) // the last token ending at or before an offset tokens.after(offset) // the first token starting at or after it tokens.at(offset) // the token containing it ``` The queries return an index, or `-1` when there is none. ## [The AST The program is plain objects: [ESTree](https://github.com/estree/estree) for JavaScript and JSX, and [TypeScript-ESTree](https://www.npmjs.com/package/@typescript-eslint/typescript-estree) for TypeScript, matching [Oxc](https://oxc.rs) down to every field. Every node has `start` and `end` in UTF-16 offsets, and the package exports the type of every node. ```ts import type { CallExpression, Expression, Node, Program } from "yuku"; ``` # Walk and build Source: https://yuku.fyi/javascript/walk/ `walk` visits a node and everything under it, depth-first in source order. From Zig, see [traversal](https://yuku.fyi/parser/traverse/). ```js import { walk } from "yuku"; walk(file.program, { Identifier(node, ctx) {}, CallExpression: { enter(node, ctx) {}, leave(node, ctx) {}, }, Function(node) {}, // declarations, expressions, and arrows enter(node) {}, // every node leave(node) {}, }); ``` Handlers are keyed by node `type`, by alias (`Expression`, `Statement`, `Declaration`, `ModuleDeclaration`, `Function`, `Class`, `Method`, `Loop`, `Pattern`, `JSX`, `TSType`), or by `enter` and `leave`. A list of visitors walks in one pass. ```js walk(file.program, [noDebugger, noConsole, preferConst]); ``` ## The context ```js ctx.parent; // null at the walk root ctx.key; // the field of the parent holding it ctx.index; // its index in an array field, or null ctx.ancestors(); // from the root down to the parent ``` The [semantic model](https://yuku.fyi/javascript/semantic/) answers for any node a walk visits, as `file.scopeOf(node)`, `file.bindingOf(node)`, and `file.referenceOf(node)`. ## Editing | Call | Effect | | ------------------------ | -------------------------------------------------------------------- | | `ctx.skip()` | Skip the children | | `ctx.stop()` | End the walk | | `ctx.replace(node)` | Put a node, or a list in an array field, in its place, then visit it | | `ctx.remove()` | Remove it | | `ctx.insertBefore(node)` | Insert a sibling the walk passes over | | `ctx.insertAfter(node)` | Insert a sibling the walk visits next | ```js walk(file.program, { DebuggerStatement(node, ctx) { ctx.remove(); }, }); ``` ## Async work A walk runs synchronously. For async work, collect the nodes in one walk, await them together, and edit in a second. ```js const calls = []; walk(file.program, { CallExpression: (node) => calls.push(node) }); const results = new Map(await Promise.all(calls.map(async (node) => [node, await rewrite(node)]))); walk(file.program, { CallExpression(node, ctx) { const result = results.get(node); if (result !== undefined) ctx.replace(result); }, }); ``` ## Build `b` has a constructor for every node type. It sets `start` and `end` to 0, and defaults each field that may be false, null, or empty. ```js import { b } from "yuku"; b.CallExpression({ callee: b.Identifier({ name: "f" }) }); // { type: "CallExpression", start: 0, end: 0, arguments: [], optional: false, callee: ... } b.ArrowFunctionExpression({ body: b.Identifier({ name: "x" }), expression: true }); // () => x ``` A field that tells the shapes of a type apart, such as `computed` on a `MemberExpression`, has no default. ## Utils `yuku/utils` has the small helpers. ```js import { decodeJSXEntities, is, isIdentifierName, isValidIdentifier, unwrap } from "yuku/utils"; is.CallExpression(node); is.Expression(node); // aliases too is.oneOf(node, ["FunctionDeclaration", "ClassDeclaration"]); is.StringLiteral(node); // also NumericLiteral, BooleanLiteral, NullLiteral, // BigIntLiteral, and RegExpLiteral is.StaticMemberExpression(node); // also ComputedMemberExpression and PrivateFieldExpression is.Directive(node); is.Wrapper(node); // parentheses or an erased TypeScript assertion unwrap(node); // the expression inside every wrapper isValidIdentifier("class"); // false, reserved isIdentifierName("class"); // true decodeJSXEntities("a & b"); // "a & b" ``` It also has `isIdentifierStart`, `isIdentifierChar`, `isKeyword`, `isReservedWord`, `isStrictReservedWord`, and `isEvalOrArguments`. # Semantic analysis Source: https://yuku.fyi/javascript/semantic/ The semantic model resolves every name in a file, values and types alike, as the TypeScript checker does. From Zig, see [semantic analysis](https://yuku.fyi/parser/semantic/). ```js const file = parse(source, { path: "app.ts", analyze: true }); file.scopes; // by id, the global scope first file.rootScope; // the module scope, or the global scope of a script file.bindings; // by id file.references; // in source order file.imports; file.exports; file.moduleFlags; // { usesRequire, usesModule, usesExports, usesImportMeta } file.bindingOf(node); // the binding it declares or refers to file.referenceOf(node); file.scopeOf(node); file.capturesOf(fn); // [{ binding, references, isWritten }] file.parentOf(node); file.ancestors(node); // the node, then each parent up to the root file.nodeAt(offset); ``` ## Scopes ```js scope.kind; // "global" | "module" | "function" | "functionBody" | "block" | "class" // | "staticBlock" | "expressionName" | "tsModule" scope.strict; scope.node; scope.parent; scope.hoistTarget; // where a var declared in it lands scope.bindings; scope.find("x"); // a binding it declares scope.lookup("x", "type"); // resolves a name as code in it would, "value" by default scope.contains(other); scope.ancestors(); ``` ## Bindings ```js binding.name; binding.scope; binding.declarations; // each declaration's name node binding.references; // its uses in this file binding.import; // the import that declares it binding.flags; // a BindingFlags bitset binding.has(BindingFlags.Function); binding.has(BindingFlags.Class | BindingFlags.Interface); // any of them binding.visibleIn("type"); binding.definition(); // { file, binding, augmentations }, following imports binding.findReferences(); // its uses across a project binding.rename("next"); ``` | Flag | Set on | | ------------------------ | --------------------------------------- | | `FunctionScopedVariable` | `var`, a parameter, or a catch variable | | `BlockScopedVariable` | `let`, `const`, `using`, `await using` | | `Function` | a function | | `Class` | a class | | `RegularEnum` | `enum` | | `ConstEnum` | `const enum` | | `ValueModule` | a namespace with runtime content | | `Interface` | `interface` | | `TypeAlias` | `type` | | `TypeParameter` | ``, `infer T`, a mapped type key | | `NamespaceModule` | a namespace of any kind | | `ValueImport` | `import x`, `import { x }` | | `TypeImport` | `import type`, `import { type x }` | | `Const` | `const`, `using`, `await using` | | `Ambient` | `declare`, or a signature with no body | | `Parameter` | a parameter | | `CatchVariable` | `catch (e)` | | `Exported` | `export`, or implicitly in ambient code | | `Default` | `export default ` | | `EnumMember` | an enum member | | `Variable` | any variable | | `Import` | any import | | `ValueSpace` | anything visible at runtime | | `TypeSpace` | anything usable as a type | | `NamespaceSpace` | what a dotted type name can start from | ## References ```js reference.name; reference.node; // the Identifier or JSXIdentifier reference.scope; reference.binding; // null for a global or undeclared name reference.space; // "value" | "type" | "namespace" | "typeof" | "any" reference.inTypePosition; reference.isWrite; // x = 1, x++, for (x of xs) ``` ## Imports and exports ```js imp.kind; // "named" | "namespace" | "sideEffect" | "importEquals" | "dynamic" // | "require" | "augmentation" imp.name; // "default" for a default import imp.local; // the binding it declares imp.specifier; imp.typeOnly; imp.phase; // "source" | "defer" | null imp.node; imp.resolvedFile; // in a project exp.kind; // "named" | "reExport" | "namespace" | "star" | "equals" | "global" exp.name; // N for export as namespace N, null for star and equals exp.local; // the binding it exports exp.specifier; exp.fromName; // the name a reExport takes exp.typeOnly; exp.node; exp.resolvedFile; ``` ## After edits The model describes the program as parsed. After a pass edits it, `file.reanalyze()` builds the model again for the program as it is now, on the same node objects, so a node added with no position resolves too. It also builds the model of a file parsed without `analyze: true`. ```js const file = parse(`let a = 1; f(a);`); const added = b.Identifier({ name: "a" }); file.program.body.push(b.ExpressionStatement({ expression: added })); file.reanalyze(); file.referenceOf(added).binding === file.rootScope.find("a"); // true ``` ## Rename `binding.rename(name)` renames a binding where it is declared and used, keeping the file's exports. ```js const file = parse(`export const a = 1;\nlet o = { a };`, { analyze: true }); file.rootScope.find("a").rename("b"); // [] print(file).code; // const b = 1; // export { b as a }; // let o = { a: b }; ``` When renaming would change what the code means, such as by shadowing or capturing another name, it changes nothing and returns the reasons as [diagnostics](https://yuku.fyi/javascript/parse/#diagnostics). ## Projects A `Project` links the imports of many files. ```js import { Project } from "yuku"; const project = new Project(); project.set("a.ts", `export const value = 1;`); project.set("b.ts", `export { value as renamed } from "./a.ts";`); const c = project.set("c.ts", `import { renamed } from "./b.ts"; renamed;`); c.rootScope.find("renamed").definition().binding.name; // "value" ``` ```js const project = new Project({ // a path in the project, false for a module outside it, null when it cannot be resolved resolve: (specifier, importer) => aliases.get(specifier) ?? null, }); project.set(path, source, options); // the SourceFile, replacing any at the same path project.delete(path); project.files; // ReadonlyMap project.diagnostics; // every file's, and the links that fail file.dependencies; // the files it imports from file.dependents; // the files that import it file.exportedNames(); file.resolveExport("x"); // { file, binding, augmentations } file.isCurrent; // false once its path is set again or deleted ``` By default, relative specifiers resolve as TypeScript resolves them, and packages are external. # Print Source: https://yuku.fyi/javascript/print/ `print` turns a file or any node back into code. From Zig, see [codegen](https://yuku.fyi/parser/codegen/). ```js import { print } from "yuku"; const { code, map, diagnostics } = print(file, { strip: true, sourceMap: true }); ``` | Option | Default | Description | | ----------- | --------------------------------------- | ----------------------------------------------------------------------------- | | `strip` | `false` | Print TypeScript as JavaScript, reporting what has no JavaScript form | | `minify` | `false` | Minify, rewriting syntax to shorter forms such as `!0` and `obj.foo` | | `format` | `"pretty"`, or `"compact"` minifying | Or `"compact"` | | `indent` | `2` | Spaces per level in the pretty format | | `quotes` | `"preserve"`, or `"shortest"` minifying | `"preserve"`, `"double"`, `"single"`, or `"shortest"` | | `comments` | `"all"`, or `"some"` minifying | `"all"`, `"some"`, `"none"`, `"line"`, or `"block"`, of the attached comments | | `sourceMap` | `false` | `true`, or `{ file, sourceRoot, sourcesContent }`, when printing a file | `"some"` keeps legal headers, JSDoc, and `@` or `#` annotations, as bundlers do. # Parser Source: https://yuku.fyi/parser/ The parser reads JavaScript, TypeScript, and JSX into a [tree](https://yuku.fyi/parser/ast/). It recovers from errors, so a parse with diagnostics still returns everything it could read. From JavaScript, see [`parse`](https://yuku.fyi/javascript/parse/). Yuku needs Zig 0.17.0 or later. ```bash zig fetch --save git+https://github.com/yuku-toolchain/yuku.git ``` ```zig // build.zig const yuku = b.dependency("yuku", .{ .target = target, .optimize = optimize }); my_module.addImport("parser", yuku.module("parser")); ``` ```zig const std = @import("std"); const parser = @import("parser"); pub fn main() !void { var tree = try parser.parse(std.heap.smp_allocator, "const x: number = 1;", .{ .lang = .ts }); defer tree.deinit(); } ``` ```zig pub fn parse(child_allocator: std.mem.Allocator, source: []const u8, options: Options) error{OutOfMemory}!ast.Tree ``` The tree lives in one arena, which `tree.deinit()` frees, and borrows `source`, which must outlive it. ## Options | Field | Default | Description | | ----------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `source_type` | `.module` | `.script`, `.module`, or `.commonjs`, whose top level is a function body | | `lang` | `.js` | `.js`, `.ts`, `.jsx`, `.tsx`, or `.dts` | | `preserve_parens` | `true` | Keep `parenthesized_expression` nodes | | `comments` | `.collect` | `.none`, `.collect`, or `.attach`, see [Comments](https://yuku.fyi/parser/ast/#comments) | | `tokens` | `false` | Keep every token, see [Tokens](https://yuku.fyi/parser/ast/#tokens) | `ast.Lang.fromPath` and `ast.SourceType.fromPath` read them from a file name. ```zig const options: parser.Options = .{ .lang = .fromPath(path), .source_type = .fromPath(path) }; ``` ## Diagnostics Every part of Yuku reports problems as an `ast.Diagnostic`. ```zig pub const Diagnostic = struct { severity: Severity = .@"error", // .@"error", .warning, .hint, or .info message: []const u8, span: Span, // bytes help: ?[]const u8 = null, labels: []const Label = &.{}, // .{ .span, .message } pointing at related code }; ``` ```zig for (tree.diagnostics.items) |d| { std.debug.print("[{s}] {s} at {d}..{d}\n", .{ d.severity.toString(), d.message, d.span.start, d.span.end }); } tree.hasErrors(); // any .@"error" try tree.addDiagnostic(.{ .message = "unused", .span = span }); ``` [Semantic analysis](https://yuku.fyi/parser/semantic/) adds the early errors that need scopes, such as redeclarations. # AST Source: https://yuku.fyi/parser/ast/ A parse returns an `ast.Tree`, a flat tree whose nodes, child lists, and strings live in arrays in one arena. From JavaScript, the tree decodes to [ESTree](https://yuku.fyi/javascript/parse/#the-ast). | Type | Is | | ------------ | -------------------------------------------------------------- | | `NodeIndex` | A node's position in `tree.nodes`, `.null` for an absent child | | `IndexRange` | A child list, a `start` and `len` in `tree.extras` | | `String` | Text, a zero-copy slice of the source or an entry in the pool | | `Span` | A source range in bytes, `start` and `end` | ## Reading ```zig tree.root // the program node tree.data(index) // its payload, a NodeData union tree.span(index) tree.extra(range) // the nodes of a child list tree.string(text) // the bytes of a String tree.source // also lang and source_type tree.isTs() // also isJsx and isModule ``` ```zig switch (tree.data(index)) { .variable_declaration => |decl| { for (tree.extra(decl.declarators)) |declarator| { _ = declarator; } }, .identifier_reference => |id| std.debug.print("{s}\n", .{tree.string(id.name)}), else => {}, } ``` `NodeData` has a tag per node kind, each the snake_case name of its payload, as in `ts_as_expression: TSAsExpression`. [ast.zig](https://github.com/yuku-toolchain/yuku/blob/main/src/parser/ast.zig) defines every one with its fields. To walk the whole tree, use the [traverser](https://yuku.fyi/parser/traverse/). ```zig data.isExpression() // also isStatement, isDeclaration, isLiteral, isPattern, // isCallable, isIteration, and isTypeContext literal.value(&tree) // a numeric literal's f64 ast.BinaryOperator.fromToken(t) // also toToken and toString, on LogicalOperator, // UnaryOperator, UpdateOperator, and AssignmentOperator kind.toString() // on VariableKind, PropertyKind, Accessibility, and the other kinds ``` ## Building and editing ```zig var tree = ast.Tree.init(allocator, ""); // or the source to edit defer tree.deinit(); const name = try tree.addString("total"); // interned const id = try tree.addNode(.{ .identifier_reference = .{ .name = name } }, span); const list = try tree.addExtra(&.{id}); // a child list tree.setData(index, data); tree.setSpan(index, span); tree.setName(index, name); // any node a declaration or reference can be tree.sourceSlice(start, end); // a String over the source, no copy tree.allocator(); // the arena ``` A built tree sets `tree.root` itself. The [transform](https://yuku.fyi/parser/traverse/#transform) traverser makes these changes during a walk. ## Comments `.comments = .collect` keeps every comment in `tree.comments`, in source order. `.attach` also gives each to the node it prints with, so it moves with its node and [codegen](https://yuku.fyi/parser/codegen/) prints it in place. ```zig pub const Comment = struct { type: Type, // .line or .block value: String, // without delimiters span: Span, // empty for an added comment position: Position, // .before, .after, or .inside an otherwise empty node same_line: bool, }; ``` ```zig var comments = tree.commentsOf(node); while (comments.next()) |comment| std.debug.print("{s}\n", .{tree.string(comment.value)}); tree.hasComments(node); tree.commentsIn(tree.span(node)); // the source comments within a span try tree.addComment(node, .{ .type = .block, .value = try tree.addString("#__PURE__") }); try tree.moveComments(from, to); // to .null drops them ``` ## Tokens `.tokens = true` keeps every token in `tree.tokens`, as the parser resolved it, ending with `eof`. ```zig for (tree.tokens) |token| std.debug.print("{t} {s}\n", .{ token.tag, token.text(tree.source) }); ``` ```zig token.span token.tag // an ast.TokenTag token.len() token.hasLineTerminatorBefore() // what ASI reads token.isEscaped() // also hasInvalidEscape and hasLoneSurrogates token.tag.toString() // its spelling, null for literals and names token.tag.precedence() // an ast.Precedence, 0 when none token.tag.isKeyword() // also isReserved, isUnconditionallyReserved, isStrictModeReserved, // isIdentifierLike, isNumericLiteral, isBinaryOperator, // isLogicalOperator, isUnaryOperator, and isAssignmentOperator tree.tokensIn(tree.span(node)) // a node's tokens, a contiguous run ``` Every node but `program`, `template_element`, and `jsx_empty_expression` starts and ends on a token boundary. ## Lexical grammar `parser.lexical` answers as the lexer does, on UTF-8 names with escapes decoded. ```zig lexical.isValidIdentifier("class"); // false, reserved, as is await lexical.isEvalOrArguments("eval"); // true, which strict code cannot bind lexical.isIdentifierName("class"); // true, reserved words included lexical.isIdentifierStart('$'); // also isIdentifierChar and isJSXIdentifierChar lexical.keyword("yield"); // ?TokenTag, contextual keywords included lexical.lineBreakLen(source, i); // 0, or the byte length of the line terminator at i try lexical.decodeStringEscapes(gpa, raw, &out); // appends WTF-8 try lexical.decodeJSXEntities(gpa, raw, &out); ``` # Semantic Analysis Source: https://yuku.fyi/parser/semantic/ Semantic analysis builds a model of a program's scopes, symbols, and references, with each reference resolved to the symbol it names, and reports the early errors that need scopes, such as redeclarations. From JavaScript, see [semantic analysis](https://yuku.fyi/javascript/semantic/). ```zig var tree = try parser.parse(allocator, source, .{}); defer tree.deinit(); const semantic = try parser.semantic.analyze(&tree, .{ .check = true }); ``` ```zig pub fn analyze(tree: *ast.Tree, options: AnalyzeOptions) error{OutOfMemory}!Semantic // .{ .check: bool } pub fn check(tree: *ast.Tree) error{OutOfMemory}!void ``` - `.check = true` appends the early errors to `tree.diagnostics` in the same walk, and `.check = false` skips their cost. - `check` reports the same errors faster, without the model. - The model lives in the tree's arena and describes the tree as parsed. Analyze again after a transform with `.check = false`, since the errors are already reported. - The [semantic traverser](https://yuku.fyi/parser/traverse/#semantic) runs hooks of your own during the analysis. ## The model ```zig semantic.symbolOf(node) // ?SymbolId, what a node declares or refers to semantic.referenceOf(node) // ?ReferenceId, at an identifier semantic.scopeOf(node) // ScopeId, the scope a node creates, or the innermost around it semantic.parentOf(node) // ?ast.NodeIndex semantic.ancestors(node) // the node, then each parent up to the root semantic.symbol(id) // also reference(id) and scopes.get(id) semantic.decls(symbol) // each declaration's name node, in source order semantic.uses(symbol) // each ReferenceId to it, in source order semantic.bindings(scope) // an iterator over the symbols a scope declares, in no order semantic.binding(scope, "x") // ?SymbolId, declared there or a var hoisting through semantic.lookup(scope, "x", .value) // ?SymbolId, as the name resolves from the scope semantic.member(ns, "x", .value) // ?SymbolId, ns.x of a namespace or enum, across merged bodies semantic.symbols // every Symbol, indexed by SymbolId, also references semantic.scopes.list // every Scope, indexed by ScopeId semantic.scopes.ancestors(id) // a scope, then each parent ``` The types are in `parser.semantic`. Ids are dense, with symbols ordered by first declaration and references by position. ```zig pub const Symbol = struct { name: ast.String, flags: Flags, // see Symbols scope: ScopeId, // where it lands, the hoist target for a var }; pub const Reference = struct { name: ast.String, scope: ScopeId, node: ast.NodeIndex, // an identifier_reference, jsx_identifier, or identifier_name symbol: SymbolId, // .none for a global or undeclared name flags: Flags, // .write, .space, and .type_position }; pub const Scope = struct { node: ast.NodeIndex, parent: ScopeId, // .none at the root hoist_target: ScopeId, kind: Kind, // .global, .module, .function, .function_body, .block, .class, // .static_block, .expression_name, or .ts_module flags: Flags, // .strict }; ``` `ScopeId.root` is the global scope, and `semantic.scopeOf(tree.root)` the scope of top-level code, the module scope in a module. A JSX component tag and a type predicate's parameter are references too, so a rename sees every use. ```zig const name = try tree.addString("renamed"); for (semantic.decls(symbol)) |node| tree.setName(node, name); for (semantic.uses(symbol)) |id| tree.setName(semantic.reference(id).node, name); ``` An enum member is also read as `E.member`, a member access rather than a reference, so a rename of one is incomplete. ```zig for (semantic.symbols, 0..) |symbol, i| { const id: parser.semantic.SymbolId = @fromBackingInt(@intCast(i)); if (semantic.uses(id).len == 0) std.debug.print("unused {s}\n", .{tree.string(symbol.name)}); } for (semantic.references) |reference| { if (reference.symbol == .none) std.debug.print("undeclared {s}\n", .{tree.string(reference.name)}); } ``` ## Scopes The scope tree follows the specification. - A catch clause shares its scope with its body, unless its parameter has a default value or a computed key. - A named function or class expression has a scope of its own for its name. - A function body scopes its `let` and `const` apart from the parameters, as TypeScript does. - A class decorator sees the scope around its class, and a member decorator sees the class scope. - Strict mode comes from modules, classes, and `"use strict"` directives. - In sloppy JavaScript, a plain function declared in a block or an `if` clause binds where a `var` of its name would, unless that `var` would be an error, as engines run it ([Annex B](https://tc39.es/ecma262/#sec-block-level-function-declarations-web-legacy-compatibility-semantics)). ## Symbols `symbol.flags` records its declaration kinds and modifiers. | Kinds | Modifiers | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------- | | `function_scoped_var`, `block_scoped_var`, `function`, `class`, `regular_enum`, `const_enum`, `value_module`, `interface`, `type_alias`, `type_parameter`, `namespace_module`, `import`, `type_import` | `const_var`, `ambient`, `parameter`, `catch_var`, `exported`, `is_default`, `enum_member` | ```zig symbol.flags.intersects(Symbol.value_space) // also variable, any_import, type_space, and namespace_space symbol.flags.visibleIn(.type) // whether a reference in a space binds to it, always for an import symbol.flags.isHoistingVar() symbol.flags.toString() ``` One rule decides merging and redeclaration. Each declaration kind has an exclusion mask in `Symbol.Excludes`, and a new declaration conflicts with a symbol whose flags intersect it, or merges into it otherwise. Function overloads, a `class` and an `interface`, and a `namespace` and an `enum` merge this way, and a namespace or enum declared in several blocks sees the members of the others. A conflicting declaration is still one of the symbol's `decls`. ## Declaration spaces A name resolves in one space, and a binding outside that space does not shadow it, as in TypeScript. ```ts type T = string; function f() { const T = 1; let x: T; // the outer type T T; // the inner const T } ``` | Space | For | | ------------ | ------------------------------------------------- | | `.value` | Runtime uses | | `.type` | Annotations | | `.namespace` | The head of a dotted name, such as `ns` in `ns.T` | | `.typeof` | A value in a type, such as `x` in `typeof x` | | `.any` | Alias positions, such as `export { x }` | `lookup` resolves by scope alone, without the position rules a reference follows, such as an `infer` type parameter being visible only in its true branch. ## Module records `module_record.collect` lists a module's imports and exports, as the specification's ImportEntry and ExportEntry records with the symbol behind each, static ones first and then dynamic ones, each in source order. ```zig const records = try parser.semantic.module_record.collect(&tree, &semantic); ``` ```zig pub const Import = struct { kind: Kind, // .named, .namespace, .side_effect, .import_equals, .dynamic, // .require, or .augmentation name: ast.String, // the imported name, "default" for a default import symbol: SymbolId, // the binding it declares, .none if it declares none specifier: ast.String, type_only: bool, phase: ?ast.ImportPhase, // .source or .@"defer" node: ast.NodeIndex, scope: ScopeId, // the body of an augmentation }; pub const Export = struct { kind: Kind, // .named, .re_export, .namespace, .star, .equals, or .global name: ast.String, symbol: SymbolId, // the binding it exports, .none for a re-export from_name: ast.String, // the name a re_export takes specifier: ast.String, type_only: bool, node: ast.NodeIndex, }; records.flags // .uses_require, .uses_module, .uses_exports, and .uses_import_meta ``` - A dynamic `import()` or `require()` counts when its specifier is a string, or a template with no substitutions. - An `augmentation` is a `declare module "m"` block in a module, which merges its body's declarations into `m`. - A declaration file that is a module with no export statement exports every declaration but its imports, as in TypeScript. - `flags` record free uses, so a local `require` does not count. # Traverse Source: https://yuku.fyi/parser/traverse/ The traverser walks a tree depth-first and calls a visitor's hooks at each node, in one of four modes. From JavaScript, see [`walk`](https://yuku.fyi/javascript/walk/). | Mode | Tracks | Returns | `ctx.tree` | | ------------------------- | ------------------------------- | ----------------------------------------- | ----------------- | | [`basic`](#visitors) | the path from the root | nothing | `*const ast.Tree` | | [`scoped`](#scoped) | the path and lexical scopes | a `ScopeTree` | `*const ast.Tree` | | [`semantic`](#semantic) | scopes, symbols, and references | the [`Semantic`](https://yuku.fyi/parser/semantic/) model | `*const ast.Tree` | | [`transform`](#transform) | the path | nothing | `*ast.Tree` | ```zig pub fn traverse(comptime V: type, tree: *ast.Tree, visitor: *V) std.mem.Allocator.Error!Result ``` `basic.traverse` takes a `*const ast.Tree`. Every mode can fail with `error.OutOfMemory`, since a subtree deeper than 256 levels walks iteratively. ## Visitors A visitor is a struct of `pub` hooks named after node tags. This one counts functions. ```zig const std = @import("std"); const parser = @import("parser"); const ast = parser.ast; const traverser = parser.traverser; const basic = traverser.basic; const Counter = struct { functions: u32 = 0, pub fn enter_function(self: *Counter, _: ast.Function, _: ast.NodeIndex, _: *basic.Ctx) traverser.Action { self.functions += 1; return .proceed; } }; var counter = Counter{}; try basic.traverse(Counter, &tree, &counter); ``` ```zig pub fn enter_(self: *V, payload: ast., index: ast.NodeIndex, ctx: *Ctx) Action pub fn exit_(self: *V, payload: ast., index: ast.NodeIndex, ctx: *Ctx) void pub fn enter_node(self: *V, data: ast.NodeData, index: ast.NodeIndex, ctx: *Ctx) Action pub fn exit_node(self: *V, data: ast.NodeData, index: ast.NodeIndex, ctx: *Ctx) void ``` - An enter hook returns an `Action`, or `std.mem.Allocator.Error!Action` to `try` an allocation. - A misspelled hook or a wrong payload type is a compile error. A hook that is not `pub` is never called. - At each node, `enter_node` runs, then `enter_` unless `enter_node` returned something other than `.proceed`, then the children in field order, then `exit_` and `exit_node`. | `Action` | Effect | | ---------- | ------------------------------------------------------------------ | | `.proceed` | Walk into the children | | `.skip` | Pass over the children. The node's exit hooks still run. | | `.stop` | End the walk. Exit hooks still run for the node and its ancestors. | Every mode's context has `ctx.tree` and `ctx.path`. ```zig ctx.path.parent() // ?ast.NodeIndex ctx.path.ancestor(n) // with the current node at 0 ctx.path.ancestors() // an iterator from the current node up ctx.path.depth() // 1 at the root ``` ## Scoped `ctx.scope` follows the walk into and out of every scope, and the walk returns every scope it saw as a `ScopeTree`. A node's own scope is current in its enter hook. This lint counts each `var` that escapes its block. ```zig const scoped = traverser.scoped; const VarInBlock = struct { found: u32 = 0, pub fn enter_variable_declaration(self: *VarInBlock, decl: ast.VariableDeclaration, _: ast.NodeIndex, ctx: *scoped.Ctx) traverser.Action { if (decl.kind == .@"var" and ctx.scope.get(ctx.scope.current).kind == .block) self.found += 1; return .proceed; } }; var lint = VarInBlock{}; const scopes = try scoped.traverse(VarInBlock, &tree, &lint); ``` ```zig ctx.scope.current // the current ScopeId ctx.scope.get(id) // its Scope, with kind, hoist_target, and flags.strict ctx.scope.ancestors(id) // an iterator from a scope up ``` ## Semantic The walk builds the [`Semantic`](https://yuku.fyi/parser/semantic/) model and returns it. A binding is declared after its node's enter hook, and references resolve when the walk ends, so a visitor collects nodes and queries the model after. This one finds the types a file imports. ```zig const sem = traverser.semantic; const TypeNames = struct { allocator: std.mem.Allocator, nodes: std.ArrayList(ast.NodeIndex) = .empty, pub fn enter_identifier_reference(self: *TypeNames, _: ast.IdentifierReference, index: ast.NodeIndex, ctx: *sem.Ctx) std.mem.Allocator.Error!traverser.Action { if (ctx.inTypePosition()) try self.nodes.append(self.allocator, index); return .proceed; } }; var names = TypeNames{ .allocator = tree.allocator() }; const semantic = try sem.traverse(TypeNames, &tree, &names); for (names.nodes.items) |node| { const id = semantic.symbolOf(node) orelse continue; // a global type if (semantic.symbol(id).flags.intersects(parser.semantic.Symbol.any_import)) std.debug.print("imported\n", .{}); } ``` ```zig ctx.inTypePosition() ctx.inTsNamespace() ctx.scope // as in scoped ctx.symbols.binding(scope, name) // ?SymbolId, a name declared so far ctx.symbols.ownBinding(scope, name) ctx.symbols.symbol(id) ``` The model covers the whole tree, so `.skip` and `.stop` only mute the visitor. ## Transform `ctx.tree` is mutable, and the walker reads a node again after its enter hook, so it walks a replacement. This one turns `price + tax` into `price * tax`. ```zig const transform = traverser.transform; const AddToMultiply = struct { pub fn enter_binary_expression(_: *AddToMultiply, expr: ast.BinaryExpression, index: ast.NodeIndex, ctx: *transform.Ctx) traverser.Action { if (expr.operator == .add) { ctx.tree.setData(index, .{ .binary_expression = .{ .left = expr.left, .right = expr.right, .operator = .multiply, } }); } return .proceed; } }; var rewrite = AddToMultiply{}; try transform.traverse(AddToMultiply, &tree, &rewrite); ``` - The tree's [building and editing](https://yuku.fyi/parser/ast/#building-and-editing) calls work during the walk. - A node whose tag a hook changes is walked, and exited, as its new kind. - After wrapping a node in a new parent, return `.skip`, so the walk does not enter it again. Modes compose as passes, such as a transform and then a semantic walk of its result. ## Your own mode A mode is a context type over one walker. ```zig pub fn walk(comptime C: type, comptime V: type, visitor: *V, ctx: *C, comptime options: traverser.Options) std.mem.Allocator.Error!void ``` A context has a `tree` field, a `*ast.Tree` to edit or a `*const ast.Tree` to read, and an optional `path: traverser.NodePath`, which its `enter` and `exit` push and pop. The walk calls these optional methods around the visitor's hooks, with the tag known at compile time. ```zig pub fn enter(self: *C, comptime tag: ast.NodeTag, index: ast.NodeIndex, data: ast.NodeData) std.mem.Allocator.Error!void pub fn post_enter(self: *C, comptime tag: ast.NodeTag, index: ast.NodeIndex, data: ast.NodeData) std.mem.Allocator.Error!void pub fn exit(self: *C, comptime tag: ast.NodeTag, index: ast.NodeIndex, data: ast.NodeData) void ``` `.whole_tree = true` calls the context for every node, even under a `.skip`, so a context that builds a model of the whole tree sees all of it. [basic.zig](https://github.com/yuku-toolchain/yuku/blob/main/src/parser/traverser/basic.zig) is the smallest mode. # Codegen Source: https://yuku.fyi/parser/codegen/ Codegen prints a tree back to source, with optional type stripping, minification, and source maps. From JavaScript, see [`print`](https://yuku.fyi/javascript/print/). ```zig var tree = try parser.parse(allocator, "const x: number = 1;", .{ .lang = .ts }); defer tree.deinit(); const result = try parser.codegen.generate(allocator, &tree, .{ .strip = true }); defer result.deinit(allocator); std.debug.print("{s}\n", .{result.code}); // const x = 1; ``` ```zig pub fn generate(allocator: std.mem.Allocator, tree: *const ast.Tree, options: Options) error{OutOfMemory}!Result pub const Result = struct { code: []const u8, diagnostics: []const ast.Diagnostic, // what strip could not print map: ?SourceMap = null, pub fn deinit(self: Result, allocator: std.mem.Allocator) void }; ``` `generate` prints from `tree.root` and leaves the tree unchanged. The result belongs to `allocator`. ## Options | Field | Default | Description | | ------------ | ----------- | --------------------------------------------------------------------- | | `strip` | `false` | Print TypeScript as JavaScript, see [Type stripping](#type-stripping) | | `minify` | `false` | Rewrite syntax to shorter forms, see [Minification](#minification) | | `format` | `.pretty` | `.pretty`, or `.compact` with only the whitespace the grammar needs | | `indent` | `2` | Spaces per level in the pretty format | | `quotes` | `.preserve` | `.preserve`, `.double`, `.single`, or `.shortest` | | `comments` | `.some` | `.some`, `.all`, `.none`, `.line`, or `.block` | | `source_map` | `null` | A `SourceMapOptions`, see [Source maps](#source-maps) | Comments print from the nodes they are [attached to](https://yuku.fyi/parser/ast/#comments), so parse with `.comments = .attach` to keep them. `.some` keeps the block comments bundlers keep: those opening with `!` or `*`, those whose text starts with `@` or `#`, and those holding `@license`, `@preserve`, or `@cc_on`. ## Type stripping `strip` prints TypeScript as JavaScript. Types, interfaces, type aliases, generics, assertions, `satisfies`, non-null `!`, `declare`, and `abstract` strip cleanly. `enum`, `namespace`, `export =`, `import = require()`, and parameter properties need new runtime code, so they are left out and reported in `diagnostics`. Their ambient forms strip silently. ## Minification `minify` rewrites syntax, and with `.compact` and `.shortest` it fully minifies. ```zig const result = try parser.codegen.generate(allocator, &tree, .{ .minify = true, .format = .compact, .quotes = .shortest, }); // const enabled = true; const size = 1000000; // prints as const enabled=!0;const size=1e6 ``` - `true` and `false` become `!0` and `!1`. - Numbers take their shortest form, so `1000000` becomes `1e6` and `0.5` becomes `.5`. - `obj["foo"]` becomes `obj.foo`, and a quoted key such as `{ "foo": x }` becomes `{ foo: x }`, where that keeps the meaning. - `` are escaped in strings and untagged templates, so the output is safe inside a `