compiler 0.0.2-preview.1

The Zena self-hosted compiler

Readme Files Dependencies Versions

compiler#

The Zena compiler, written in Zena. It parses, type-checks, and compiles Zena source code to WebAssembly (Wasm GC) and WebAssembly Text (WAT).

Usage#

Parsing a Single File#

Use compiler/parser to parse Zena source text into an AST (Module):

import { parse } from 'compiler/parser';

let ast = parse('export let answer = 42;', 'example.zena');

Loading and Checking a Program#

Use compiler (createCompiler and checkCompilation) with a CompilerHost to resolve imports across a module graph and type-check a program:

import {
  createCompiler, checkCompilation, buildStdlibConfig
} from 'compiler';
import { FsCompilerHost } from 'compiler/fs-host';

let stdlibRoot = '/stdlib';
let host = new FsCompilerHost(stdlibRoot);
let packages = buildStdlibConfig(stdlibRoot, 'host');
let compiler = createCompiler(host, {
  stdlibRoot,
  packages,
});

let result = await compiler.compile({
  entry: '/workspace/main.zena',
  target: 'host',
});
let checked = checkCompilation(result);

Compiling a File to WebAssembly#

Use compiler/compile-file to compile an entry file on disk to a .wasm or .wat output file:

import { compileFile } from 'compiler/compile-file';

let ok = await compileFile({
  entry: 'src/main.zena',
  outPath: 'out/main.wasm',
  stdlibRoot: '/stdlib',
});

Libraries#

  • compiler / compiler/compiler — compiler entry point (Compiler, createCompiler, checkCompilation, ProgramCheckResult)
  • compiler/compile-file — end-to-end file compilation (compileFile, CompileFileOptions)
  • compiler/tokenizer — lexer and token definitions (tokenize, Token, TokenType)
  • compiler/parser — recursive-descent parser (parse, Parser)
  • compiler/ast — AST node definitions (Node, Module, Statement, Expression, TypeAnnotation)
  • compiler/visitor — AST traversal helpers (walk, Visitor)
  • compiler/scope — lexical scope and symbol resolution (ScopeBuilder, ScopeResult, Symbol)
  • compiler/checker — static type checker (checkModule, CheckResult)
  • compiler/semantic-model — semantic queries over a checked module (SemanticModel)
  • compiler/types — compiler type representations (Type, ClassType, FunctionType, typeToString)
  • compiler/diagnostics — compiler diagnostics and source spans (Diagnostic, DiagnosticCode, DiagnosticSeverity, SourceSpan)
  • compiler/package-manifest — zena-package.json manifest and workspace loader (loadWorkspace, loadPackageMap)
  • compiler/module-resolver — package and relative module specifier resolution (ModuleResolver, PackageConfig)
  • compiler/library-loader — module graph loader (LibraryLoader, CompilerHost, SourceFile)
  • compiler/codegen/binary-generator — WebAssembly GC binary emitter (BinaryGenerator)
  • compiler/codegen/wat-generator — WebAssembly Text (WAT) emitter (WatGenerator)

License#

MIT

5.1 KiB Raw
/**
 * Wall-time measurement for the compiler's own phases: `performance`
 * accumulates the time spent under each named phase, over the
 * standard library's monotonic clock, which every target supplies.
 *
 * A phase keeps a total and a call count, and `phases()` returns them
 * in the order each name was first measured. `--time` prints that list,
 * so a `performance.start` added anywhere in the compiler appears in
 * the report without a line being added for it.
 *
 * `start` and `end` allocate a Measure per call. That is nothing for a
 * phase entered once per compile and too much for one entered once per
 * function; for those, read `nowMs` into a local, accumulate over the
 * loop, and `add` the total once at the end.
 */

import { monotonic } from 'zena:time';

/** The monotonic clock, in milliseconds. */
export function nowMs(): f64 {
  return ((monotonic() as i64) as f64) / 1000000.0;
}

final class Measure {
  name: String;
  startTime: f64;
  new(this.name, this.startTime);
}

/**
 * One phase's accumulated time and call count. Only `Performance`
 * writes the fields; a caller reads them off `phases()`.
 */
export final class Phase {
  name: String;
  /** Milliseconds accumulated under this name. */
  var total: f64 = 0.0;
  /** How many measures have closed under this name. */
  var count: i32 = 0;
  new(this.name);
}

/**
 * Named phase timings. `start` opens a measure and returns its id;
 * `end` closes it and adds its duration to the phase's total.
 */
export final class Performance {
  var #nextId: i32 = 0;
  // How many nested compiles deep we are. A depth rather than a flag
  // so that a nested compile inside a nested compile still resumes at
  // the right level.
  var #suspendDepth: i32 = 0;
  #active = new Map<i32, Measure>();
  #byName = new Map<String, Phase>();
  // The same phases in the order each was first measured, which is the
  // order they run in, and so the order to report them in.
  var #inOrder = new GrowableArray<Phase>();

  /**
   * Stops recording until the matching `resume`, for a nested compile
   * whose phases would otherwise be added to the enclosing compile's.
   *
   * A compile inside a compile — the component target builds the
   * runtime memory module this way — loads, parses and checks its own
   * files, and counting that work in the same totals made the report
   * exceed wall-clock time: once inside the phase that contains the
   * nested compile, and again in the top-level `load`, `parse`,
   * `scope` and `check`. The nested compile's own breakdown is lost,
   * which is the price; the caller still times it as one phase.
   */
  suspend(): void {
    this.#suspendDepth += 1;
  }

  /** Resumes recording. See `suspend`. */
  resume(): void {
    if (this.#suspendDepth > 0) {
      this.#suspendDepth -= 1;
    }
  }

  start(name: String): i32 {
    if (this.#suspendDepth > 0) {
      // -1 is not a key in `#active`, so the matching `end` is a no-op.
      return -1;
    }
    // Register the phase now rather than when it closes, so that a
    // phase that encloses others is ordered — and so reported — ahead
    // of them. `check` opens first and closes last.
    this.#phase(name);
    let id = this.#nextId;
    this.#nextId += 1;
    this.#active[id] = new Measure(name, nowMs());
    return id;
  }

  end(id: i32): f64 {
    if (this.#active.has(id)) {
      let measure = this.#active[id];
      this.#active.delete(id);
      let duration = nowMs() - measure.startTime;
      this.add(measure.name, duration);
      return duration;
    }
    return 0.0;
  }

  /**
   * Adds `ms` to `name` without opening a measure: for a phase timed
   * with `nowMs` around a loop, where a Measure per iteration would
   * cost more than the phase being measured.
   *
   * `times` is how much to raise the count by, for a counter kept in a
   * local across a loop and reported once. Counting in the loop and
   * reporting after it keeps the hot path free of both the clock and
   * the map lookup, which matters where the thing being counted is the
   * reason the loop is hot.
   */
  add(name: String, ms: f64, times: i32 = 1): void {
    if (this.#suspendDepth > 0) {
      return;
    }
    let phase = this.#phase(name);
    phase.total = phase.total + ms;
    phase.count = phase.count + times;
  }

  #phase(name: String): Phase {
    if (let (true, existing) = this.#byName.get(name)) {
      return existing;
    }
    let created = new Phase(name);
    this.#byName[name] = created;
    this.#inOrder.push(created);
    return created;
  }

  getDuration(name: String): f64 {
    if (let (true, phase) = this.#byName.get(name)) {
      return phase.total;
    }
    return 0.0;
  }

  getCount(name: String): i32 {
    if (let (true, phase) = this.#byName.get(name)) {
      return phase.count;
    }
    return 0;
  }

  /** Every phase measured so far, in the order each was first measured. */
  phases(): GrowableArray<Phase> {
    let all = new Array<Phase>(this.#inOrder.length);
    for (let phase in this.#inOrder) {
      all.push(phase);
    }
    return all;
  }

  clear(): void {
    this.#active.clear();
    this.#byName.clear();
    this.#inOrder = new GrowableArray<Phase>();
  }
}

export let performance = new Performance();
VersionPublishedDependenciesApproved by
0.0.2-preview.1 2026-11-19