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

3.4 KiB Raw
import { targetEmitsComponent, targetUsesZenaComponentHost } from './targets.zena';
import { HashMap } from 'zena:collections';

// Build the standard prelude map (module specifier → imported names).
// The compiler injects these into every file automatically.
// Explicit strings to import are used to limit namespace pollution.
// Note: Some primitive types (i32, f64, Array) are injected as language built-ins
// during scope resolution, so they don't need to be explicitly imported.
//
// The prelude is per-target because it is an import list like any
// other, and a virtual module resolves per target — but the list is
// the same on every target: `console` included, so that code that
// prints is portable. A target with no host to print to gets the
// component's console. See docs/design/component-emission.md, Part 3.
export function getStandardPrelude(target: String): HashMap<String, FixedArray<String>> {
  let prelude = new Map<String, FixedArray<String>>();

  // One entry for what used to be thirteen. The names are unchanged —
  // they are the same declarations, reached through the library that
  // owns them now that its members have no module names of their own.
  prelude["zena:core"] = [
    "String", "StringIndex",
    "StringGraphemes", "StringCodePoints", "StringUtf8View", "StringUtf16View",
    "Error", "IndexOutOfBoundsError", "ContractError", "unreachable",
    "Option", "Some", "None", "some", "none",
    "Iterator", "Iterable", "Step",
    "Array", "MutableArray",
    "Range", "BoundedRange", "FromRange", "ToRange", "FullRange",
    "ImmutableArray", "FixedArray", "GrowableArray",
    "Equatable", "Hashable", "Stringable", "toString", "Box", "Resource",
    "i32ToString", "i64ToString", "f64ToString",
    "parseI32", "parseI64", "parseF64"
  ];
  // On every target, so that code that prints is portable. A target
  // with no host to print to gets the component's console, which is
  // what a hostless core module is once wrapped.
  prelude["zena:console"] = ["console"];
  prelude["zena:collections"] = ["Map", "HashMap"];
  prelude["zena:async"] = ["Future", "Awaited"];
  return prelude;
}

/**
 * Modules a target links whether or not the program names them.
 *
 * Not a prelude: the prelude is the list of names bound into every file,
 * and these bind nothing. They are here because the compiler
 * synthesizes calls into them, and a module it generates calls into has
 * to be in the graph before reachability runs. Reachability still
 * decides whether any of it is emitted — a component that moves no
 * strings links none of `zena:wasi`'s marshaling.
 *
 * Loaded **after** the entry point. Reachability roots a module's
 * exports by iterating `globalDeclarations`, which is in declaration
 * order, so a module loaded ahead of the entry no longer permutes what
 * the entry emits — it used to, when that map iterated in symbol-id
 * hash order. Loading afterwards is still the tidier shape: the
 * entry's symbol ids are the same with or without the runtime
 * modules, which keeps the component target's core module identical
 * to a hostless build's for one more reason than the ordered map.
 */
export function getTargetRuntimeModules(target: String): FixedArray<String> {
  if (targetUsesZenaComponentHost(target)) {
    // `zena-runtime` supplies `Error`'s stack traces through a module
    // the component entry calls before `main`.
    return ["zena:wasi", "zena:host-setup"];
  }
  if (targetEmitsComponent(target)) {
    return ["zena:wasi"];
  }
  return new Array<String>.fixed(0, "");
}
VersionPublishedDependenciesApproved by
0.0.2-preview.1 2026-11-19