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

4.6 KiB Raw
/**
 * Structural `==` on records and tuples (docs/design/equality.md,
 * "Structural equality for records and tuples"). Two operands compare
 * through one synthesized function per pair of operand types
 * (ir/equality.zena, `lowerValueEqFunction`), which reachability
 * registers and lowering calls. This module is what the two agree on:
 * which operands compare, which fields pair up, and the function's key.
 */
import { CallExpression, MemberExpression, Node } from '../ast.zena';
import { SemanticModel, memberKeyOf } from '../semantic-model.zena';
import { NullType, RecordType, TupleType, Type, UnionType, VoidType } from '../types.zena';
import { compareStrings, getTypeUniqueKey, unwrapAliases } from './codegen-utils.zena';

/**
 * A record or tuple operand's type without `| null` and without an alias,
 * or null for any other type.
 */
export function valueEqOperand(t: Type): Type | null {
  var base = unwrapAliases(t);
  if (base is UnionType) {
    var only: Type | null = null;
    var count = 0;
    for (let m in base.types) {
      if (!(m is NullType)) {
        only = m;
        count += 1;
      }
    }
    if (count != 1 || only == null) {
      return null;
    }
    base = unwrapAliases(only);
  }
  if (base is RecordType || base is TupleType) {
    return base;
  }
  return null;
}

/**
 * Whether `t` is an existential record type, `{x: i32, ...}`, whose
 * `==` and hash are those of the record it holds (ir/existential.zena).
 */
export function isExistentialRecord(t: Type): boolean {
  let base = unwrapAliases(t);
  if (base is RecordType) {
    let rec = base;
    return rec.isExistential;
  }
  return false;
}

/**
 * One pair of fields two operands compare: a record field by name, or a
 * tuple element by its index written as a string (its struct field's
 * name).
 */
export final class ValueEqField {
  name: String;
  left: Type;
  right: Type;
  leftOptional: boolean;
  rightOptional: boolean;
  new(this.name, this.left, this.right, this.leftOptional, this.rightOptional);
}

/**
 * The fields `l` and `r` compare pairwise, records in field-name order,
 * or null when the two never hold equal values: records with different
 * field names, tuples of different lengths, or a record and a tuple.
 * `==` does not convert its operands, so a record is never equal to one
 * with other fields (row-types.md, Decisions).
 */
export function valueEqFields(l: Type, r: Type): GrowableArray<ValueEqField> | null {
  let out = new Array<ValueEqField>();
  if (l is TupleType && r is TupleType) {
    let ls = l.elementTypes;
    let rs = r.elementTypes;
    if (ls.length != rs.length) {
      return null;
    }
    for (var i = 0; i < ls.length; i += 1) {
      // A zero-width element has no field and nothing to compare.
      if (ls[i] is VoidType && rs[i] is VoidType) {
        continue;
      }
      out.push(new ValueEqField(`${i}`, ls[i], rs[i], false, false));
    }
    return out;
  }
  if (l is RecordType && r is RecordType) {
    if (l.properties.size != r.properties.size) {
      return null;
    }
    let names = new Array<String>();
    for (let name in l.properties.keys()) {
      if (!r.properties.has(name)) {
        return null;
      }
      names.push(name);
    }
    for (var i = 1; i < names.length; i += 1) {
      let key = names[i];
      var j = i - 1;
      while (j >= 0 && compareStrings(names[j], key) > 0) {
        names[j + 1] = names[j];
        j -= 1;
      }
      names[j + 1] = key;
    }
    for (let name in names) {
      out.push(new ValueEqField(name, l.properties[name], r.properties[name],
          l.isOptional(name), r.isOptional(name)));
    }
    return out;
  }
  return null;
}

/** The key of the comparison function for operand types `l` and `r`. */
export function valueEqKey(l: Type, r: Type): String {
  return `${getTypeUniqueKey(l)}|${getTypeUniqueKey(r)}`;
}

/** The key of the hash function for the record or tuple type `t`. */
export function valueHashKey(t: Type): String {
  return getTypeUniqueKey(t);
}

/**
 * Whether `call`, with callee `member` on a receiver of type `receiver`,
 * is `hashCode()` on a record or tuple: records and tuples satisfy
 * `Hashable`, so generic code bounded by it calls `hashCode()` on them,
 * and that call hashes the value. A record with its own `hashCode` field
 * calls that instead.
 */
export function isValueHashCodeCall(call: CallExpression, member: MemberExpression,
    receiver: Type, model: SemanticModel): boolean {
  if (call.args.length != 0 || member.optional || member.isSymbolAccess) {
    return false;
  }
  let v = valueEqOperand(receiver);
  if (v == null || memberKeyOf(model, member.property as Node) != 'hashCode') {
    return false;
  }
  let t = v as Type;
  return !(t is RecordType && t.properties.has('hashCode'));
}
VersionPublishedDependenciesApproved by
0.0.2-preview.1 2026-11-19