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
3.4 KiB
Raw
import { Program, CompilationUnit } from '../../program.zena';
import { SemanticModel } from '../../semantic-model.zena';
import { ImportSpecifier, ImportDeclaration, Module } from '../../ast.zena';
import { Type, FunctionType } from '../../types.zena';
import { Symbol, SymbolId, noSymbolId } from '../../scope/symbol.zena';
import { dirName, normalizePath } from '../../module-resolver.zena';
function matchOverloadForImport(fnType: Type, expectedType: Type): boolean {
if (!(fnType is FunctionType) || !(expectedType is FunctionType)) {
return false;
}
return fnType.parameters.length == expectedType.parameters.length;
}
export function resolveImportedSymbolId(program: Program, model: SemanticModel, spec: ImportSpecifier, expectedType: Type | null = null): SymbolId {
var parentNode = model.getParent(spec);
if (parentNode == null) {
for (let u in program.units) {
if (u.model == model || u.ast.path == model.sourcePath) {
for (let stmt in u.ast.body) {
if (stmt is ImportDeclaration) {
for (let s in stmt.imports) {
if (s == spec || s.imported.name == spec.imported.name) {
parentNode = stmt;
break;
}
}
}
}
break;
}
}
}
if (parentNode == null || !(parentNode is ImportDeclaration)) {
return noSymbolId;
}
let specifier = parentNode.moduleSpecifier.value;
var canonicalPath = specifier;
if (specifier.startsWith("./") || specifier.startsWith("../")) {
let referrer = model.getParent(parentNode);
if (referrer is Module) {
let dir = dirName(referrer.path);
canonicalPath = normalizePath(`${dir}/${specifier}`);
}
}
// Exact only. `Program` indexes every unit under its canonical path and,
// for a stdlib unit, under the module name the manifest gives it, so an
// import that resolves at all resolves here. Searching for a unit whose
// file name ends the same way used to stand in for that index being
// wrong, and matched any path with the right last segment.
let targetUnitOpt: CompilationUnit | null = if (program.unitsByPath.has(canonicalPath)) program.unitsByPath[canonicalPath] else null;
if (targetUnitOpt == null) {
// Not an error: a module outside this program's units is one whose
// symbols nothing here can reach, and the caller treats an unresolved
// import as nothing to root.
return noSymbolId;
}
let targetUnit = targetUnitOpt as CompilationUnit;
let importedName = spec.imported.name;
let key1 = `${targetUnit.ast.path}::${importedName}`;
let key2 = `${canonicalPath}::${importedName}`;
let listOpt: GrowableArray<Symbol> | null = if (program.exportedSymbols.has(key1)) {
program.exportedSymbols[key1]
} else if (program.exportedSymbols.has(key2)) {
program.exportedSymbols[key2]
} else {
null
};
if (listOpt != null) {
let list = listOpt;
var fallback: Symbol | null = null;
for (let sym in list) {
if (expectedType == null) {
return sym.id;
}
let declNode = sym.declaration;
if (declNode != null) {
let nodeType = targetUnit.model.getNodeType(declNode);
if (nodeType != null && matchOverloadForImport(nodeType, expectedType)) {
return sym.id;
}
}
if (fallback == null) { fallback = sym; }
}
if (fallback != null) {
return fallback.id;
}
}
return noSymbolId;
}
- 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 |
|
|