Yuku
Dialects
A dialect adds your own syntax to JavaScript, TypeScript, or JSX, from one operator to a whole language. You write only what is new, in one Zig file compiled into the parser: where your syntax starts, how it reads, the shape and scope of its nodes, and how they print.
Yuku does everything else. It parses the rest of the language around your syntax and inside it, builds the semantic model with your scopes and bindings in it, walks and transforms your nodes, and prints them, from Zig and from JavaScript. All of it comes with the same correctness, spec compliance, and speed as standard code.
Example
A pipeline operator, |>, with % as the value piped in.
// src/pipeline.zig
const std = @import("std");
const yuku = @import("parser");
const ast = yuku.ast;
const dialect = yuku.dialect;
pub const files: []const dialect.File = &.{.{ .extension = ".pipe.js", .lang = .js }};
pub const Node = enum {
pipeline,
topic,
pub fn shape(node: Node) dialect.Shape {
return switch (node) {
.pipeline => .{ .type = "PipelineExpression", .fields = &.{ "left", "right" } },
.topic => .{ .type = "TopicReference" },
};
}
};
pub fn operator(p: *dialect.Parser, left: ast.NodeIndex, precedence: u8) dialect.Error!dialect.Claim {
if (!std.mem.startsWith(u8, p.tree().source[p.token().span.start..], "|>")) return .decline;
if (precedence > ast.Precedence.Assignment) return .end;
if (!try p.advance() or !try p.advance()) return .failed;
const right = try p.parseExpression(ast.Precedence.Assignment + 1) orelse return .failed;
const span: ast.Span = .{ .start = p.tree().span(left).start, .end = p.tree().span(right).end };
return .{ .node = try p.addNode(.pipeline, &.{ left, right }, span) };
}
pub fn expression(p: *dialect.Parser) dialect.Error!dialect.Claim {
const token = p.token();
if (token.tag != .percent) return .decline;
if (!try p.advance()) return .failed;
return .{ .node = try p.addNode(.topic, &.{}, token.span) };
}
pub fn print(w: *dialect.Printer, kind: Node, children: []const ast.NodeIndex) void {
switch (kind) {
.pipeline => {
w.node(children[0]);
w.write(" |> ");
w.node(children[1]);
},
.topic => w.write("%"),
}
}
In prices |> sum(%) |> round(%, 2), the pipelines group left to right, the calls in them are standard nodes, and each pipeline is { type: "PipelineExpression", start, end, left, right } in JavaScript.
The dialect file
A dialect is a Zig file of public declarations, which imports the parser it is compiled into as @import("parser").
| Declaration | Required | Purpose |
|---|---|---|
files | yes | The files it reads |
Node | to add nodes | Your node kinds |
| Position functions | at least one | Where your syntax starts |
print | to print your nodes | How codegen prints them |
Files
pub const files: []const dialect.File = &.{
.{ .extension = ".pipe.js", .lang = .js },
.{ .extension = ".pipe.ts", .lang = .ts },
};
Each is an extension and the standard lang the dialect extends in those files. In Zig, a parse with .dialect = true reads the dialect, as in .{ .lang = .js, .dialect = true }. In JavaScript, the path picks it, see From JavaScript.
Positions
A position is where the parser asks your dialect first, through the pub fn of that name.
| Position | Asked at |
|---|---|
statement | The start of every statement |
expression | The start of every operand, before any prefix operator, and at a @ after export default |
operator | After the operand left, where an infix or postfix operator could follow |
function_body | Where a function, method, or arrow function body starts |
jsx_child | Each JSX child, at byte offset in parent |
jsx_attribute | A { in a JSX tag, where standard JSX reads a spread attribute |
jsx_element_name | The start of an element name, in an opening or closing tag |
module_specifier | A module specifier that is not a string |
pub fn statement(p: *dialect.Parser) dialect.Error!dialect.Claim
pub fn expression(p: *dialect.Parser) dialect.Error!dialect.Claim
pub fn operator(p: *dialect.Parser, left: ast.NodeIndex, precedence: u8) dialect.Error!dialect.Claim
pub fn function_body(p: *dialect.Parser) dialect.Error!dialect.Claim
pub fn jsx_child(p: *dialect.Parser, offset: u32, parent: ast.NodeIndex) dialect.Error!dialect.Claim
pub fn jsx_attribute(p: *dialect.Parser) dialect.Error!dialect.Claim
pub fn jsx_element_name(p: *dialect.Parser) dialect.Error!dialect.Claim
pub fn module_specifier(p: *dialect.Parser) dialect.Error!dialect.Claim
dialect.Claim | Means |
|---|---|
.decline | Not your syntax. Consume no tokens and add no nodes. |
.{ .node = index } | The node you added, with the current token just past it. |
.failed | A diagnostic was reported, by you or by a parse call. |
.end | operator only. The expression ends before the current token. |
- Positions apply inside your own nodes too, so your syntax and standard syntax nest.
- Decline anything the standard grammar accepts, unless you mean to read it differently.
operatorreceives the lowestprecedencethat continues the current expression. Answer.endwhen your operator binds more loosely, as the example does.function_bodyallowsreturnand a directive prologue inside.- A
jsx_childnode starts atoffsetand ends on its last token, which stays current.parentis the opening element or fragment. Callseek(offset)first when the child starts with tokens.
The parser
*dialect.Parser | Does |
|---|---|
token() | The current ast.Token |
advance() | Moves to the next token, or returns false after a lexical error |
expect(tag, message) | Consumes a token of tag, or reports message and returns false |
tokenAt(offset) | The token at or after a byte offset, without moving |
seek(offset) | Makes the token at a byte offset current, at or after the current one |
semicolon(end) | Ends a statement, with ; or where one is inserted, returning its end, or null after a diagnostic |
report(span, message) | Reports an error |
parseStatement() | Parses a statement |
parseExpression(precedence) | Parses an expression binding at precedence or tighter, ast.Precedence.Lowest for a whole one |
parseBindingPattern() | Parses an identifier, array, or object pattern, with its type annotation |
toPattern(expression, context) | Turns an expression into the .binding or .assignable pattern it is written as, as [a, b] = c does |
parseJsxExpressionContainer() | Parses the { expression } at the current { in a tag |
parseJsxElement() | Parses the element or fragment at the current <, leaving its last > current |
addNode(kind, children, span) | Adds one of your nodes |
list() | A dialect.List that collects children of unknown count |
addJsxText(span) | Adds the source text in a non-empty span as JSX text |
recordComment(type, span) | Records a comment where the standard grammar reads none, in source order |
canAwait() | Whether await is an operator here, in an async function or a module’s top level |
endDirectivePrologue() | Ends the directive prologue of a function_body, at its first part that is no statement |
tree() | The ast.Tree, to read nodes and build standard ones |
A parse call returns null after it reports a diagnostic, and then you answer .failed.
var children = p.list();
defer children.deinit();
while (p.token().tag != .right_brace) {
try children.append(try p.parseStatement() orelse return .failed);
}
const node = try p.addNode(.block, children.items(), span);
Nodes
Node is an enum of your node kinds, counting up from 0, whose shape describes each one.
pub const Node = enum {
each,
pub fn shape(node: Node) dialect.Shape {
return switch (node) {
.each => .{
.type = "EachStatement",
.fields = &.{ "item", "list", "body[]" },
.block_scope = true,
.lexical_bindings = true,
},
};
}
};
dialect.Shape | Default | Means |
|---|---|---|
type | The node’s type in JavaScript | |
fields | &.{} | Its children in order, where one name ending in [] takes the rest as an array |
properties | "{}" | A JSON object of constant properties every node of the kind has in JavaScript |
block_scope | false | The node opens a block scope |
lexical_bindings | false | Each binding identifier inside declares a let-like binding in the current scope |
catch_bindings | false | Each binding identifier inside declares a catch parameter |
iteration | false | The node is a loop, which break and continue end or skip |
switch | false | The node is a switch, which break ends |
text | false | The node is the source text of its span, which it prints and is in JavaScript |
addNode takes children in fields order, .null for an absent one, inside span. In the tree, the node is an ast.Dialect, its kind a dialect.Kind and its children a range for tree.extra. In JavaScript it is a plain object of its type, start, end, properties, and fields, so each (item of list) { ... } is { type: "EachStatement", start, end, item, list, body: [...] }, and a text node is a string.
Printing
pub fn print(w: *dialect.Printer, kind: Node, children: []const ast.NodeIndex) void
*dialect.Printer | Does |
|---|---|
write(code) | Writes code, with a space before it where needed |
space() | Writes a space in the pretty format |
node(index) | Prints any node, standard or yours |
block(items) | Prints a list of statements between braces |
tree() | The tree, to read nodes |
Text nodes print themselves. Without print, codegen reports a diagnostic for each of your other nodes.
Analysis and walking
Semantic analysis walks into your nodes. Standard code inside them declares, resolves, and reports early errors as usual, and the shape decides the scope and bindings your node adds. Every traverser mode reaches your nodes through enter_dialect and exit_dialect, and a transform can replace them with standard ones to compile your syntax to JavaScript.
Building
Pass your dialect file to the yuku dependency.
// build.zig
const yuku = b.dependency("yuku", .{
.target = target,
.optimize = optimize,
.dialect = b.path("src/pipeline.zig"),
});
my_module.addImport("parser", yuku.module("parser"));
b.installArtifact(@import("yuku").addWasm(b, yuku, "pipeline"));
@import("yuku").addAddons(b, yuku);
yuku.module("parser")is the Zig parser with your dialect compiled in.addWasm(b, yuku, name)buildszig-out/bin/<name>.wasm, the WebAssembly core theyukupackage runs.addAddons(b, yuku)buildszig-out/native/<platform>.node, the Node-API addon for each platform the package ships, from any machine.
A parser without a dialect has no dialect code. With one, a standard file pays one flag check per position. Inside the Yuku repository, zig build wasm addon -Ddialect=src/pipeline.zig builds the core for this platform.
From JavaScript
A Core runs the compiled dialect, as the core option of parse, new Project, and print.
import { readFileSync } from "node:fs";
import { Core, parse, print } from "yuku";
const wasm = new WebAssembly.Module(readFileSync("zig-out/bin/pipeline.wasm"));
const core = new Core({ wasm });
const file = parse("const total = prices |> sum(%);", { path: "app.pipe.js", core });
print(file).code; // "const total = prices |> sum(%);"
print(file.program.body[0], { core }).code; // the same, from the node
- A path ending in one of your extensions reads the dialect, and so does a source without a path.
- Any other path, or a given
lang, reads standard syntax. - Your nodes walk, analyze, and print like standard ones, and
printandreanalyze()take them back to Zig after you edit them.
Declare your nodes in DialectNodes to type them.
import type { BaseNode, Expression } from "yuku";
declare module "yuku" {
interface DialectNodes {
PipelineExpression: BaseNode & { type: "PipelineExpression"; left: Expression; right: Expression };
TopicReference: BaseNode & { type: "TopicReference" };
}
}
A package for a dialect ships its core, so its users parse without one. Give Core the addons too, each URL its own literal so bundlers and deploy tracers find the binaries.
import { Core, parse as parseYuku, type ParseOptions, type SourceFile } from "yuku";
import wasm from "./pipeline.wasm"; // base64, from your bundler
const core = new Core({
wasm,
addons: {
"darwin-arm64": () => new URL("./native/darwin-arm64.node", import.meta.url),
"linux-x64": () => new URL("./native/linux-x64.node", import.meta.url),
},
});
export function parse(source: string, options: Omit<ParseOptions, "core"> = {}): SourceFile {
return parseYuku(source, { ...options, core });
}