compiler 0.0.2-preview.1
The Zena self-hosted compiler
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.jsonmanifest 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
6.3 KiB
Raw
import { Node, InterfaceDeclaration, TypeAliasDeclaration, TypeParameter,
ClassDeclaration, EnumDeclaration, MixinDeclaration,
ImportSpecifier, SealedVariant, IdGenerator
} from '../ast.zena';
/**
* Distinct type for Symbol identity keys.
* Prevents accidental use of arbitrary i32 values as symbol IDs.
*/
export distinct type SymbolId = i32;
/**
* The only way to get SymbolIds. See `makeNodeIdGenerator` in ast.zena for why
* the conversion lives here rather than being exported on its own.
*/
export function makeSymbolIdGenerator(nextId: i32 = 1): IdGenerator<SymbolId> {
return new IdGenerator<SymbolId>((id: i32) => id as SymbolId, nextId);
}
/**
* The absence of a symbol, and the only SymbolId that is not minted by a
* generator.
*
* Two situations share it, because both mean "there is no declaration behind
* this" and generated ids start at 1, so no real id can collide:
*
* - A synthetic type — an inferred class, a specialization, a function type
* with no declared name — permanently has no symbol.
* - A `Scope.declare` / `Symbol` call that supplies no id, asking the scope's
* generator to mint one.
*
* Named rather than written as `-1 as SymbolId` at 60-odd call sites so that
* this file stays the only place a SymbolId is minted, which is what `opaque`
* would require if SymbolId ever became one.
*/
export let noSymbolId = -1 as SymbolId;
/**
* Information about a declared name in a scope.
*
* Stored in scope bindings. The `declaration` field references the
* AST node that introduced this name.
*
* Each Symbol has a unique `id` that can be used as a HashMap key
* by downstream passes (e.g., the type checker maps id → Type).
*/
export final class Symbol {
/**
* Unique identity for this binding.
* Enables identity-keyed maps (Map<SymbolId, T>) without requiring object-identity hashing.
*/
id: SymbolId;
/**
* Whether this binding can be reassigned (defined with `var` instead of `let`).
*
* Implementation Note: We track this directly on the Symbol rather than querying
* the `declaration` node. The `declaration` field usually points to a leaf
* pattern (like an `IdentifierPattern`), which doesn't know if it was bound by
* a `let` or `var`. Since Zena AST nodes lack parent pointers, the checker
* cannot traverse upward to check the parent `VariableDeclaration`.
*
* TODO: Immutability is better resolved during type checking rather than scope
* analysis. Scope building cannot easily account for complex mutability rules
* like accessors with getters but no setters, or the true mutability of imported
* cross-module exports. We should eventually move mutability checks fully to the
* checker. To handle the lack of AST parent pointers, the checker could build
* parent references dynamically during its traversal, or we can pass the explicit
* parent declaration node downward to the leaf patterns.
*/
isMutable: boolean;
/**
* The AST node at the binding site, or null for built-in types.
*
* Points to the most specific node that introduces the name:
* - Simple variables (`let x = 5`): IdentifierPattern
* - Destructured variables (`let {x, y} = p`): each IdentifierPattern
* - Functions (annotated, predeclared): IdentifierPattern
* - Parameters: Parameter
* - Classes: ClassDeclaration
* - Interfaces: InterfaceDeclaration
* - Enums: EnumDeclaration
* - Mixins: MixinDeclaration
* - Type aliases: TypeAliasDeclaration
* - Imports: ImportSpecifier
* - Pattern bindings (match): the leaf pattern node
* - Built-ins (i32, boolean, etc.): null
*
* The checker stores each binding's type on this node via
* SemanticModel.setNodeType(declaration, type). Reference sites
* follow ReferenceMap → Symbol → declaration → getNodeType
* to recover the type.
*/
declaration: Node | null;
/**
* The module path where this symbol was declared.
* Empty string for built-in types and locals/parameters.
*/
modulePath: String;
name: String;
var importTarget: Symbol | null = null;
/**
* For module-level `let`/`var` bindings: whether the initializer is
* a function expression, and whether its signature is fully written
* (a binding annotation, or every parameter plus the return type
* annotated). Consumed by the import-cycle rules
* (docs/design/import-cycles.md): only fully annotated functions may
* cross a cycle's back edge.
*/
var isFunctionBinding: boolean = false;
var hasFullSignature: boolean = false;
/**
* The implicit `context` of a field decorator's body: the decorated
* field's name and accessors (docs/design/decorators.md, "The
* decorated field's context"). Declared by the scope builder on the
* decorator's subject name; its type is bound by the checker.
*/
var isDecoratorContext: boolean = false;
/** Set by the checker when a decorator body reads its `context`. */
var decoratorContextUsed: boolean = false;
new(
this.name: String,
this.declaration: Node | null,
this.modulePath: String,
this.isMutable: boolean = false,
// Inlined rather than `noSymbolId`: a constructor default cannot
// reference a module-level binding. Same value, same meaning.
this.id: SymbolId = -1 as SymbolId);
resolveTarget(): Symbol {
var current = this;
while (current.importTarget != null) {
current = current.importTarget as Symbol;
}
return current;
}
// TODO: `isValue()` and `isType()` shouldn't belong on `Symbol`.
// For cross-module imports (`ImportSpecifier`), the true namespace
// depends on the actual exported declaration in the target module.
// These should be moved to the Checker which can follow import links.
isValue(): boolean {
return match (this.declaration) {
case null: false
case InterfaceDeclaration: false
case TypeAliasDeclaration: false
case TypeParameter: false
case _: true
};
}
isType(): boolean {
return match (this.declaration) {
case null: true
case ClassDeclaration: true
case InterfaceDeclaration: true
case EnumDeclaration: true
case MixinDeclaration: true
case TypeAliasDeclaration: true
case ImportSpecifier: true // Conservatively true
case TypeParameter: true
case SealedVariant: true
case _: false
};
}
}
- zena-lang:wit-parser wit-parser.zena-lang.pkg.zena-lang.dev ~0.0.1-preview.1
| Version | Published | Dependencies | Approved by |
|---|---|---|---|
| 0.0.2-preview.1 | 2026-11-19 |
|
|