Yuku

Parser

The parser reads JavaScript, TypeScript, and JSX into a tree. It recovers from errors, so a parse with diagnostics still returns everything it could read. From JavaScript, see parse.

Yuku needs Zig 0.17.0 or later.

zig fetch --save git+https://github.com/yuku-toolchain/yuku.git
// build.zig
const yuku = b.dependency("yuku", .{ .target = target, .optimize = optimize });
my_module.addImport("parser", yuku.module("parser"));
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();
}
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

FieldDefaultDescription
source_type.module.script, .module, or .commonjs, whose top level is a function body
lang.js.js, .ts, .jsx, .tsx, or .dts
preserve_parenstrueKeep parenthesized_expression nodes
comments.collect.none, .collect, or .attach, see Comments
tokensfalseKeep every token, see Tokens

ast.Lang.fromPath and ast.SourceType.fromPath read them from a file name.

const options: parser.Options = .{ .lang = .fromPath(path), .source_type = .fromPath(path) };

Diagnostics

Every part of Yuku reports problems as an ast.Diagnostic.

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
};
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 adds the early errors that need scopes, such as redeclarations.