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.7 KiB
Raw
/**
* Diagnostic infrastructure for the Zena compiler.
*
* Diagnostics are errors and warnings produced by the checker and other
* compiler passes. They are collected in a DiagnosticBag and reported
* to the user.
*/
import { SourceLocation } from './ast.zena';
import { lineAt, columnAt } from './line-index.zena';
/**
* The span a diagnostic reports for a node's location: the location's
* own file when it has one (the node may belong to another module than
* the one being checked), else `file`; line and column derived from
* the start offset.
*/
export function spanOf(loc: SourceLocation, file: String): SourceSpan {
let path = loc.path ?? file;
return new SourceSpan(path, loc.start, loc.end - loc.start,
lineAt(path, loc.start), columnAt(path, loc.start));
}
export enum DiagnosticSeverity {
Error,
Warning,
Information
}
/**
* Each diagnostic has a unique code for programmatic identification.
* Ranges:
* 1000-1999: Parser errors
* 2000-2999: Checker errors
* 3000-3999: Checker warnings
*/
export enum DiagnosticCode {
// Parser Errors
UnexpectedToken,
ExpectedToken,
StatementOutsideFunction,
// Checker Errors
TypeMismatch,
SymbolNotFound,
DuplicateDeclaration,
InvalidAssignment,
ReturnOutsideFunction,
ArgumentCountMismatch,
PropertyNotFound,
NotCallable,
NotIndexable,
GenericTypeArgumentMismatch,
ConstructorInMixin,
AbstractMethodInConcreteClass,
AbstractMethodNotImplemented,
CannotInstantiateAbstractClass,
ModuleNotFound,
IndexOutOfBounds,
InvalidOperator,
BreakOutsideLoop,
ContinueOutsideLoop,
UnreachableCode,
UninitializedField,
MissingReturnType,
IncompatibleTypes,
InvalidCast,
NonExhaustiveMatch,
InvalidPattern,
CircularType,
DuplicateField,
DuplicateMethod,
PrivateAccess,
ReadonlyAssignment,
CyclicImport,
OpaqueTypeCast,
UnjustifiedTypeParameterCast,
UseAfterMove,
/** An expression that must change nothing, a `static` condition or the argument of `old`, has an effect. */
ImpureExpression,
// Warnings
UnusedVariable,
NeverMutatedVariable,
UnusedImport,
UnusedImportedSymbol,
UnnecessaryImport,
DuplicateImport,
ShadowedVariable,
UnnecessaryNullish,
UnnecessaryCast,
/** An interface, function or record adaptation the compiler inserts: an allocation here and an indirect call per use. */
Adaptation,
/** A statement discards an owner that a call, `new` or `await` produced, which is released at once. */
DiscardedOwner,
// Internal compiler errors
UnknownError,
}
/**
* Points to a specific location in source code.
*/
export final class SourceSpan(
file: String,
start: i32,
length: i32,
line: i32,
column: i32
)
/**
* A single diagnostic message (error, warning, or info).
*/
export final class Diagnostic(
code: DiagnosticCode,
message: String,
severity: DiagnosticSeverity,
location: SourceSpan | null
)
/**
* Collects diagnostics during a compiler pass.
*/
export final class DiagnosticBag {
#diagnostics: GrowableArray<Diagnostic>;
#file: String;
new(file: String)
: #diagnostics = new Array<Diagnostic>(),
#file = file;
// Report a diagnostic directly.
report(diagnostic: Diagnostic): void {
this.#diagnostics.push(diagnostic);
}
// Report an error with a message and optional source location.
reportError(message: String, code: DiagnosticCode, loc: SourceLocation | null): void {
var location: SourceSpan | null = null;
if (loc != null) {
location = spanOf(loc, this.#file);
} else {
// Even without a source location, include the file for context.
location = new SourceSpan(this.#file, 0, 0, 0, 0);
}
this.#diagnostics.push(new Diagnostic(
code, message, DiagnosticSeverity.Error, location
));
}
// Report a warning with a message and optional source location.
reportWarning(message: String, code: DiagnosticCode, loc: SourceLocation | null): void {
var location: SourceSpan | null = null;
if (loc != null) {
location = spanOf(loc, this.#file);
} else {
// Even without a source location, include the file for context.
location = new SourceSpan(this.#file, 0, 0, 0, 0);
}
this.#diagnostics.push(new Diagnostic(
code, message, DiagnosticSeverity.Warning, location
));
}
// Whether any error-level diagnostics have been reported.
hasErrors(): boolean {
var i = 0;
while (i < this.#diagnostics.length) {
if (this.#diagnostics[i].severity == DiagnosticSeverity.Error) {
return true;
}
i += 1;
}
return false;
}
#compareDiagnostics(a: Diagnostic, b: Diagnostic): i32 {
let locA = a.location;
let locB = b.location;
if (locA == null && locB == null) { return 0; }
if (locA == null) { return -1; }
if (locB == null) { return 1; }
let lA = locA as SourceSpan;
let lB = locB as SourceSpan;
if (lA.line != lB.line) { return lA.line - lB.line; }
if (lA.column != lB.column) { return lA.column - lB.column; }
return lA.start - lB.start;
}
#sortDiagnostics(): void {
var i = 1;
while (i < this.#diagnostics.length) {
let current = this.#diagnostics[i];
var j = i - 1;
while (j >= 0 && this.#compareDiagnostics(this.#diagnostics[j], current) > 0) {
this.#diagnostics[j + 1] = this.#diagnostics[j];
j -= 1;
}
this.#diagnostics[j + 1] = current;
i += 1;
}
}
// All collected diagnostics.
diagnostics: GrowableArray<Diagnostic> {
get {
this.#sortDiagnostics();
return this.#diagnostics;
}
}
}
/**
* A syntax error in the source being compiled.
*
* The parser throws this when it cannot go on. Its `message` is already
* formatted for a terminal (`file:line:column - Error: `, the offending
* line, and an underline of the token), and `diagnostic` carries the
* structured span and message for an editor or language service.
*/
export class SyntaxError extends Error {
diagnostic: Diagnostic;
new(message: String, diagnostic: Diagnostic)
: diagnostic = diagnostic, super(message);
}
/**
* Format a diagnostic as a human-readable string.
*/
export function formatDiagnostic(d: Diagnostic, source: String): String {
var result = "";
match (d.severity) {
case DiagnosticSeverity.Error: { result = "error"; }
case DiagnosticSeverity.Warning: { result = "warning"; }
case DiagnosticSeverity.Information: { result = "info"; }
}
if (d.location != null) {
let loc = d.location as SourceSpan;
// If line/column are 0, only show the file name (no precise location).
if (loc.line == 0 && loc.column == 0) {
result = `${result} [${loc.file}]`;
} else {
result = `${result} [${loc.file}:${loc.line}:${loc.column}]`;
}
}
result = `${result}: ${d.message}`;
return result;
}
- 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 |
|
|