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
43.3 KiB
Raw
/**
* Pattern lowering, split out of lowering.zena: the refutable-test
* and binding emitters that match arms, let-conditions, and
* destructuring declarations all share, plus the pure pattern
* algebra (refutability, binds, bound-symbol collection). The
* ORCHESTRATION stays in lowering.zena — #lowerMatch and friends own
* the environment save/restore, reachability, and merge state — and
* calls in here for everything per-pattern. Each function takes the
* shared LoweringContext; bodies are streaming's shapes exactly.
*/
import {
AbsencePattern, AsPattern, AssignmentPattern, BindingPattern,
BindingProperty, BooleanLiteral, ClassPattern, Expression, Identifier,
IdentifierPattern, LiteralPattern, LogicalPattern, MemberExpression,
Node, NullLiteral, NumberLiteral, RecordPattern, StringLiteral,
TuplePattern, ArrayPattern, RestPattern,
} from '../../ast.zena';
import {
ClassType, InterfaceType, NullType, RecordType, Type, UnionType,
} from '../../types.zena';
import {
typeToValTypeWithSub,
} from '../type-mapping.zena';
import { Symbol, SymbolId } from '../../scope/symbol.zena';
import {
ValType, ValTypeAnyRef, ValTypeEqRef, ValTypeF32, ValTypeF64,
ValTypeI32, ValTypeI64, ValTypeI8, ValTypeI16, ValTypeRef, ValTypeRefNull, isRefValType,
valTypeEquals,
} from '../wasm.zena';
import {
RecordDispatchInfo, WasmStruct, WasmArray, asWasmStruct, asWasmArray, asWasmSignature, isValSubtype,
} from '../wasm-module.zena';
import { getClassKey, getClassMethodKey, parseFloatLiteral, parseI64OrU64Literal, presentWordName, unwrapAliases } from '../codegen-utils.zena';
import { IrOp, IrRefField, IrRefFunc, IrRefType } from './ir.zena';
import {
LoweringContext, ZirUnsupported, noValues, oneValue, twoValues,
} from './lowering-context.zena';
import { lowerBigIntLiteral, lowerStringLiteral } from './templates.zena';
import { bindTupleWithRest, inlineMembersMatching, lowerExpr, recordRestValue, repackRecordUnion, tupleRestIndexOf, unboxTuples } from './lowering.zena';
/** Bail with the lowering-side message shape (reason @function). */
let bail = (cx: LoweringContext, reason: String): never => {
throw new ZirUnsupported(reason + ' @' + (cx.func.name ?? '?'));
};
/**
* The value a record pattern destructures. A pattern whose value is a
* union of record types carries an adaptation to the one shape the
* checker merged for it: the member the value is repacks to that shape
* here, and everything downstream — the presence mask, guarded
* defaults, nested patterns — works against a single record type.
*/
let recordPatternValue = (cx: LoweringContext, rp: RecordPattern,
value: i32): i32 => {
let raOpt = cx.func.model.getRecordUnionAdaptation(rp as Node);
if (raOpt != null) {
return repackRecordUnion(cx, raOpt, value);
}
// A record union narrowed to one member, by the arms before this one or
// by a comparison of its discriminant: the value is that member, held
// as the union, so it is cast to the member's fat pointer.
if (recordDispatchOfValue(cx, value) == null && isRefValType(cx.valueTypeOf(value))) {
let matchedOpt = cx.substitutedNodeType(rp as Node);
if (matchedOpt != null) {
let matched = unwrapAliases(matchedOpt);
if (matched is RecordType) {
let d = cx.recordDispatchOf(matched);
return cx.conformToSlot(value, new ValTypeRef(d.fatPtrType) as ValType,
'record pattern on a narrowed union');
}
}
}
return value;
};
/** Branches to `failB` when `cond` is false; continues in a new block. */
export let branchUnless = (cx: LoweringContext, cond: i32, failB: i32): void => {
let contB = cx.b.newBlock();
cx.b.brIf(cond, contB, noValues(), failB, noValues());
cx.b.switchTo(contB);
};
/** ref.test `value` against `st`, branching to `failB` on failure. */
let emitRefTest = (cx: LoweringContext, value: i32, st: WasmStruct,
failB: i32): void => {
let vt = cx.valueTypeOf(value);
if (!isRefValType(vt)) {
bail(cx, 'type test operand');
}
let targetVt = new ValTypeRef(st) as ValType;
let cond = cx.b.emit(IrOp.ref_test, new ValTypeI32(), value,
cx.b.internType(targetVt));
branchUnless(cx, cond, failB);
};
/** The struct a class lowers to; ZirUnsupported when undiscovered. */
let classStructOf = (cx: LoweringContext, ct: ClassType): WasmStruct => {
if (let (true, info) = cx.wasm.classInfos.get(getClassKey(ct))) {
return info.structType;
}
throw new ZirUnsupported('pattern class not discovered');
};
/**
* The type test of a pattern that names a class or interface: `case
* Foo:`, or `case Iterable<i32>:`. Branches to `failB` when `value` is
* not one.
*/
let lowerNamedTypeTest = (cx: LoweringContext, patType: Type, value: i32,
failB: i32): void => {
if (patType is ClassType) {
emitRefTest(cx, value, classStructOf(cx, patType), failB);
} else if (patType is InterfaceType) {
if (cx.typeTestHasSlot(patType)) {
// `case I:` means the value's class implements `I`
// (docs/design/interface-type-tests.md).
let cond = cx.typeTestImplements(value, patType);
branchUnless(cx, cond, failB);
} else {
let targetVt = typeToValTypeWithSub(cx.wasm, patType, cx.func);
let stOpt = asWasmStruct(targetVt);
if (stOpt == null) {
bail(cx, 'pattern interface not discovered');
} else {
emitRefTest(cx, value, stOpt, failB);
}
}
}
};
/**
* The values of a tuple pattern's elements when `value` is a boxed union of
* tuples rather than one tuple struct, as an element of a boxed tuple can
* be (#1040): the union read into slots, and each element's value for the
* members the pattern's literals allow. Null when `value` is a struct.
*/
function unionTupleLanes(cx: LoweringContext, tp: TuplePattern, value: i32,
nodes: GrowableArray<Node | null>): GrowableArray<i32> | null {
if (asWasmStruct(cx.valueTypeOf(value)) != null) {
return null;
}
let t = cx.substitutedNodeType(tp as Node);
if (t == null) {
return null;
}
let source = unboxTuples(cx, value, t);
if (source == null) {
return null;
}
let lanes = source;
let layout = lanes.layout;
let allowed = if (layout != null) inlineMembersMatching(layout, tp.elements) else null;
return lanes.patternValues(cx, tp.elements, allowed, nodes);
}
/** The struct behind a (boxed) tuple or class value; bails otherwise. */
let structOfValue = (cx: LoweringContext, value: i32): WasmStruct => {
let stOpt = asWasmStruct(cx.valueTypeOf(value));
if (stOpt == null) {
bail(cx, 'pattern operand kind');
}
return stOpt;
};
/** The record dispatch whose fat-pointer struct backs `value`, if any. */
export let recordDispatchOfValue = (cx: LoweringContext,
value: i32): RecordDispatchInfo | null => {
let stOpt = asWasmStruct(cx.valueTypeOf(value));
if (stOpt == null) {
return null;
}
for (let info in cx.wasm.recordDispatchInfos) {
if (info.fatPtrType == stOpt) {
return info;
}
}
return null;
};
/** The boxed-tuple field value at `index` of a tuple-struct value. */
let tupleFieldRead = (cx: LoweringContext, value: i32, index: i32): i32 => {
let st = structOfValue(cx, value);
let fieldName = i32ToString(index);
let fieldIdx = st.fieldIndexByName(fieldName);
if (fieldIdx < 0) {
// A zero-width element (`void`) has no field, and no value; the
// checker has already matched the pattern's length to the type's.
return -1;
}
let fieldRef = cx.b.addRef(new IrRefField(st, fieldName));
return cx.b.emit(IrOp.struct_get, st.fields[fieldIdx].type, value, fieldRef);
};
/** `case "lit":` — a direct call to String.==, mirroring streaming. */
let stringPatternEq = (cx: LoweringContext, value: i32,
sl: StringLiteral, failB: i32): i32 => {
if (cx.wasm.stringClass == null) {
bail(cx, 'string pattern without String class');
}
let sc = cx.wasm.stringClass as ClassType;
let st = classStructOf(cx, sc);
let key = getClassMethodKey(getClassKey(sc), "==");
let eqFunc = if (let (true, f) = cx.wasm.classMethodMap.get(key)) f else null;
if (eqFunc == null) {
bail(cx, 'string pattern without String.==');
}
let sig = eqFunc.signature;
if (sig.returns.length != 1 || sig.params.length != 2) {
bail(cx, 'String.== shape');
}
let have = cx.valueTypeOf(value);
var rawRecv = value;
if (!(have is ValTypeRef && have.target == st)) {
emitRefTest(cx, value, st, failB);
let nonNullVt = new ValTypeRef(st) as ValType;
rawRecv = cx.b.emit(IrOp.ref_cast, nonNullVt, value,
cx.b.internType(nonNullVt));
}
let lit = lowerStringLiteral(cx, sl);
let recv = cx.conformReceiver(rawRecv, sig.params[0], 'string pattern operand');
if (!isValSubtype(cx.valueTypeOf(lit), sig.params[1])) {
bail(cx, 'string pattern operand');
}
let funcRef = cx.b.addRef(new IrRefFunc(eqFunc));
return cx.b.callFunc(funcRef, twoValues(recv, lit), sig.returns[0]);
};
/** `case 0:` / `case 42n:` against a BigInt (or nullable/any) scrutinee. */
function lowerBigIntPatternTest(cx: LoweringContext, value: i32,
num: NumberLiteral, failB: i32) {
if (cx.wasm.bigIntClass == null) {
bail(cx, 'bigint pattern without BigInt class');
}
let bc = cx.wasm.bigIntClass as ClassType;
let st = classStructOf(cx, bc);
let key = getClassMethodKey(getClassKey(bc), "==");
let eqFunc = if (let (true, f) = cx.wasm.classMethodMap.get(key)) f else null;
if (eqFunc == null) {
bail(cx, 'bigint pattern without BigInt.==');
}
let sig = eqFunc.signature;
if (sig.returns.length != 1 || sig.params.length != 2) {
bail(cx, 'BigInt.== shape');
}
let have = cx.valueTypeOf(value);
var recv = value;
if (!(have is ValTypeRef && have.target == st)) {
emitRefTest(cx, value, st, failB);
let nonNullVt = new ValTypeRef(st) as ValType;
recv = cx.b.emit(IrOp.ref_cast, nonNullVt, value,
cx.b.internType(nonNullVt));
}
let recvArg = cx.conformReceiver(recv, sig.params[0], 'bigint pattern operand');
let lit = cx.coerceTo(lowerBigIntLiteral(cx, num.raw, false), sig.params[1]);
let funcRef = cx.b.addRef(new IrRefFunc(eqFunc));
let cond = cx.b.callFunc(funcRef, twoValues(recvArg, lit), sig.returns[0]);
branchUnless(cx, cond, failB);
}
/** The length of an array (wasm array or struct with #length / get:length). */
export let arrayLengthRead = (cx: LoweringContext, value: i32): i32 => {
let arrOpt = asWasmArray(cx.valueTypeOf(value));
if (arrOpt != null) {
return cx.b.emit(IrOp.array_len, new ValTypeI32(), value, -1);
}
let stOpt = asWasmStruct(cx.valueTypeOf(value));
if (stOpt != null) {
let st = stOpt;
for (let field in st.fields) {
if (field.name != null && (field.name as String).endsWith('#length')) {
let name = field.name as String;
let fieldRef = cx.b.addRef(new IrRefField(st, name));
return cx.b.emit(IrOp.struct_get, field.type, value, fieldRef);
}
}
if (st.fields.length == 2) {
let vstOpt = asWasmStruct(st.fields[1].type);
if (vstOpt != null) {
let vst = vstOpt;
var slot = vst.fieldIndexByName('get#length');
var slotName = 'get#length';
if (slot < 0) {
slot = vst.fieldIndexByName('length');
slotName = 'length';
}
if (slot < 0) {
slot = vst.fieldIndexByName('get:length');
slotName = 'get:length';
}
if (slot >= 0) {
let sigOpt = asWasmSignature(vst.fields[slot].type);
if (sigOpt != null) {
let sig = sigOpt;
let inst = cx.b.emit(IrOp.iface_instance, st.fields[0].type, value, -1);
let vt = cx.b.emit(IrOp.iface_vtable, st.fields[1].type, value, -1);
let fieldRef = cx.b.addRef(new IrRefField(vst, slotName));
let callee = cx.b.emit(IrOp.struct_get, vst.fields[slot].type, vt, fieldRef);
let args = oneValue(inst);
let retType = if (sig.returns.length > 0) sig.returns[0] else null;
return cx.b.callRef(callee, args, retType);
}
}
}
}
}
bail(cx, 'array pattern length');
};
/** The array element value at `index` of an array or sliceable struct. */
export let arrayElementRead = (cx: LoweringContext, value: i32, index: i32): i32 => {
let arrOpt = asWasmArray(cx.valueTypeOf(value));
if (arrOpt != null) {
let arr = arrOpt;
let idxVal = cx.b.constI32(index, new ValTypeI32());
let op = if (arr.elementType is ValTypeI8 || arr.elementType is ValTypeI16) {
IrOp.array_get_u
} else {
IrOp.array_get
};
let vt = if (arr.elementType is ValTypeI8 || arr.elementType is ValTypeI16) {
new ValTypeI32() as ValType
} else {
arr.elementType
};
return cx.b.emit(op, vt, value, idxVal);
}
let stOpt = asWasmStruct(cx.valueTypeOf(value));
if (stOpt != null) {
let st = stOpt;
for (let field in st.fields) {
if (field.name != null && (field.name as String).endsWith('#buffer')) {
let name = field.name as String;
let fieldRef = cx.b.addRef(new IrRefField(st, name));
let bufVal = cx.b.emit(IrOp.struct_get, field.type, value, fieldRef);
return arrayElementRead(cx, bufVal, index);
}
}
if (st.fields.length == 2) {
let vstOpt = asWasmStruct(st.fields[1].type);
if (vstOpt != null) {
let vst = vstOpt;
let slotName = indexReadSlotName(vst);
if (slotName != null) {
let slot = vst.fieldIndexByName(slotName);
let sigOpt = asWasmSignature(vst.fields[slot].type);
if (sigOpt != null) {
let sig = sigOpt;
let inst = cx.b.emit(IrOp.iface_instance, st.fields[0].type, value, -1);
let vt = cx.b.emit(IrOp.iface_vtable, st.fields[1].type, value, -1);
let fieldRef = cx.b.addRef(new IrRefField(vst, slotName));
let callee = cx.b.emit(IrOp.struct_get, vst.fields[slot].type, vt, fieldRef);
let idxVal = cx.b.constI32(index, new ValTypeI32());
let args = twoValues(inst, idxVal);
let retType = if (sig.returns.length > 0) sig.returns[0] else null;
return cx.b.callRef(callee, args, retType);
}
}
}
}
}
bail(cx, 'array element read');
};
/**
* The name of the interface vtable slot that reads one element by index,
* or null when there is none. When `[]` is overloaded (`Array<T>` also
* slices by range), each overload has its own slot, named by its
* signature key, and this is the one whose parameter is an i32.
*/
let indexReadSlotName = (vtable: WasmStruct): String | null => {
if (vtable.fieldIndexByName('[]') >= 0) {
return '[]';
}
for (let field in vtable.fields) {
let {name} = field;
if (name != null && name.startsWith('[]$')) {
let signature = asWasmSignature(field.type);
if (signature != null && signature.params.length == 2 &&
signature.params[1] is ValTypeI32) {
return name;
}
}
}
return null;
};
/** Slices an array from `startIndex` to the end, returning a new FixedArray. */
export let arraySliceRead = (cx: LoweringContext, value: i32, startIndex: i32): i32 => {
let len = arrayLengthRead(cx, value);
let startVal = cx.b.constI32(startIndex, new ValTypeI32());
let sliceLen = cx.b.binary(IrOp.i32_sub, new ValTypeI32(), len, startVal);
let zero = cx.b.constI32(0, new ValTypeI32());
var buf = value;
var arrOpt = asWasmArray(cx.valueTypeOf(value));
if (arrOpt == null) {
let stOpt = asWasmStruct(cx.valueTypeOf(value));
if (stOpt != null) {
let st = stOpt;
for (let field in st.fields) {
if (field.name != null && (field.name as String).endsWith('#buffer')) {
let name = field.name as String;
let fieldRef = cx.b.addRef(new IrRefField(st, name));
buf = cx.b.emit(IrOp.struct_get, field.type, value, fieldRef);
arrOpt = asWasmArray(cx.valueTypeOf(buf));
break;
}
}
if (arrOpt == null && st.fields.length == 2) {
let vstOpt = asWasmStruct(st.fields[1].type);
if (vstOpt != null) {
let vst = vstOpt;
let slotName = indexReadSlotName(vst);
if (slotName != null) {
let slot = vst.fieldIndexByName(slotName);
let sig = asWasmSignature(vst.fields[slot].type);
if (sig != null && sig.returns.length > 0) {
// An interface-typed receiver hides which array backs it:
// `Array<T>` is satisfied by both `(array (mut T))` and
// `(array T)`. The copy branches on the instance's actual
// representation — array.copy reads from either, only the
// destination must be mutable.
let elemVt = sig.returns[0];
let mutArr = cx.wasm.getArray(elemVt, true);
let mutRefVt = new ValTypeRef(mutArr) as ValType;
let immArr = cx.wasm.getArray(elemVt, false);
let immRefVt = new ValTypeRef(immArr) as ValType;
let inst = cx.b.emit(IrOp.iface_instance, st.fields[0].type, value, -1);
let destPair = cx.b.pushExtra(twoValues(sliceLen, -1));
let dest = cx.b.emit(IrOp.array_new, mutRefVt, destPair, cx.b.addRef(new IrRefType(mutArr)));
let isMut = cx.b.emit(IrOp.ref_test, new ValTypeI32(), inst, cx.b.internType(mutRefVt));
let mutB = cx.b.newBlock();
let immB = cx.b.newBlock();
let doneB = cx.b.newBlock();
cx.b.brIf(isMut, mutB, noValues(), immB, noValues());
cx.b.switchTo(mutB);
let castMut = cx.b.emit(IrOp.ref_cast, mutRefVt, inst, cx.b.internType(mutRefVt));
let mutTuple = new Array<i32>();
mutTuple.push(dest);
mutTuple.push(zero);
mutTuple.push(castMut);
mutTuple.push(startVal);
mutTuple.push(sliceLen);
cx.b.emitVoid(IrOp.array_copy, cx.b.pushExtra(mutTuple), -1);
cx.b.br(doneB, noValues());
cx.b.switchTo(immB);
let castImm = cx.b.emit(IrOp.ref_cast, immRefVt, inst, cx.b.internType(immRefVt));
let immTuple = new Array<i32>();
immTuple.push(dest);
immTuple.push(zero);
immTuple.push(castImm);
immTuple.push(startVal);
immTuple.push(sliceLen);
cx.b.emitVoid(IrOp.array_copy, cx.b.pushExtra(immTuple), -1);
cx.b.br(doneB, noValues());
cx.b.switchTo(doneB);
return dest;
}
}
}
}
}
}
if (arrOpt != null) {
// The slice is a fresh array and array.copy needs a mutable
// destination, so build it mutable whatever the source's element
// mutability (the checker types the rest slice mutable too).
let arrType = cx.wasm.getArray((arrOpt as WasmArray).elementType, true);
let destPair = cx.b.pushExtra(twoValues(sliceLen, -1));
let dest = cx.b.emit(IrOp.array_new, new ValTypeRef(arrType) as ValType, destPair, cx.b.addRef(new IrRefType(arrType)));
let copyTuple = new Array<i32>();
copyTuple.push(dest);
copyTuple.push(zero);
copyTuple.push(buf);
copyTuple.push(startVal);
copyTuple.push(sliceLen);
let copyTupleIdx = cx.b.pushExtra(copyTuple);
cx.b.emitVoid(IrOp.array_copy, copyTupleIdx, -1);
return dest;
}
bail(cx, 'array slice read');
};
/** Whether `pattern` can fail to match (needs a fail edge). */
export let patternRefutable = (cx: LoweringContext, pattern: Node): boolean => {
return match (pattern) {
case IdentifierPattern: false
case Identifier as ident: {
if (ident.name == "_") {
false
} else {
let t = cx.func.model.getNodeType(pattern);
t is ClassType || t is InterfaceType
}
}
case AsPattern as ap: patternRefutable(cx, ap.pattern)
case BindingPattern as bp: patternRefutable(cx, bp.pattern)
case LogicalPattern as lp: {
if (lp.operator == "||") {
patternRefutable(cx, lp.left) && patternRefutable(cx, lp.right)
} else {
patternRefutable(cx, lp.left) || patternRefutable(cx, lp.right)
}
}
case TuplePattern as tp: {
var refutable = false;
for (let el in tp.elements) {
if (el != null && patternRefutable(cx, el)) {
refutable = true;
}
}
refutable
}
case ArrayPattern: true
case RestPattern as rp: patternRefutable(cx, rp.pattern)
case RecordPattern as rp: {
var refutable = false;
// An optional field named without a default is a presence test —
// the matched record type is stamped on the pattern node by the
// checker (absent in irrefutable contexts, where the checker
// requires a default instead).
let tOpt = cx.func.model.getNodeType(rp);
let recOpt: RecordType | null =
if (tOpt is RecordType) tOpt else null;
for (let prop in rp.properties) {
if (recOpt != null && recOpt.isOptional(prop.name.name) &&
!(prop.value is AssignmentPattern)) {
refutable = true;
}
if (patternRefutable(cx, prop.value)) {
refutable = true;
}
}
refutable
}
case AssignmentPattern as ap: patternRefutable(cx, ap.left)
case AbsencePattern: true
case _: true
};
};
/** Whether `pattern` introduces any bindings. */
export let patternBinds = (cx: LoweringContext, pattern: Node): boolean => {
return match (pattern) {
case IdentifierPattern as pat: pat.name != "_"
case Identifier as ident: {
if (ident.name == "_") {
false
} else {
let sym = cx.func.model.resolveDeclaration(ident);
sym != null && !sym.isType()
}
}
case AsPattern: true
case BindingPattern as bp: patternBinds(cx, bp.pattern)
case LiteralPattern: false
case ClassPattern as cp: {
var binds = false;
for (let prop in cp.properties) {
if (patternBinds(cx, prop.value)) {
binds = true;
}
}
binds
}
case LogicalPattern as lp:
patternBinds(cx, lp.left) || patternBinds(cx, lp.right)
case TuplePattern as tp: {
var binds = false;
for (let el in tp.elements) {
if (el != null && patternBinds(cx, el)) {
binds = true;
}
}
binds
}
case ArrayPattern as ap: {
var binds = false;
for (let el in ap.elements) {
if (el != null && patternBinds(cx, el)) {
binds = true;
}
}
binds
}
case RestPattern as rp: patternBinds(cx, rp.pattern)
case RecordPattern as rp: {
var binds = false;
for (let prop in rp.properties) {
if (patternBinds(cx, prop.value)) {
binds = true;
}
}
let rest = rp.rest;
if (rest != null && patternBinds(cx, rest)) {
binds = true;
}
binds
}
case AssignmentPattern as ap: patternBinds(cx, ap.left)
case _: false
};
};
/** All symbols a pattern binds, in source order. */
export let collectPatternBindSyms = (cx: LoweringContext, pattern: Node,
out: GrowableArray<SymbolId>): void => {
if (pattern is IdentifierPattern) {
if (pattern.name != "_") {
let sym = cx.func.model.resolveDeclaration(pattern);
if (sym != null) {
out.push(sym.id);
}
}
return;
}
if (pattern is Identifier) {
if (pattern.name != "_") {
let sym = cx.func.model.resolveDeclaration(pattern);
if (sym != null && !sym.isType()) {
out.push(sym.id);
}
}
return;
}
if (pattern is AsPattern) {
let sym = cx.func.model.resolveDeclaration(pattern.name);
if (sym != null) {
out.push(sym.id);
}
collectPatternBindSyms(cx, pattern.pattern, out);
return;
}
if (pattern is BindingPattern) {
collectPatternBindSyms(cx, pattern.pattern, out);
return;
}
if (pattern is TuplePattern) {
for (let el in pattern.elements) {
if (el != null) {
collectPatternBindSyms(cx, el, out);
}
}
return;
}
if (pattern is ArrayPattern) {
for (let el in pattern.elements) {
if (el != null) {
collectPatternBindSyms(cx, el, out);
}
}
return;
}
if (pattern is RestPattern) {
collectPatternBindSyms(cx, pattern.pattern, out);
return;
}
if (pattern is RecordPattern) {
for (let prop in pattern.properties) {
collectPatternBindSyms(cx, prop.value, out);
}
let rest = pattern.rest;
if (rest != null) {
collectPatternBindSyms(cx, rest, out);
}
return;
}
if (pattern is ClassPattern) {
for (let prop in pattern.properties) {
collectPatternBindSyms(cx, prop.value, out);
}
return;
}
if (pattern is LogicalPattern) {
collectPatternBindSyms(cx, pattern.left, out);
if (pattern.operator != "||") {
collectPatternBindSyms(cx, pattern.right, out);
}
return;
}
if (pattern is AssignmentPattern) {
collectPatternBindSyms(cx, pattern.left, out);
}
};
/**
* Emits the refutable tests for `pattern` against `value`, branching
* to `failB` at the first failure; on success execution falls through
* in the current block. Pattern kinds not modeled yet bail here.
*/
export let lowerPatternTest = (cx: LoweringContext, pattern: Node,
value: i32, failB: i32): void => {
match (pattern) {
case IdentifierPattern: {}
case Identifier as ident: {
if (ident.name != "_") {
// `case Foo:` where Foo names a class or interface is a type test;
// any other identifier is an irrefutable binding (mirrors
// streaming's check emitter).
let patType = cx.substitutedNodeType(pattern);
if (patType != null) {
lowerNamedTypeTest(cx, patType, value, failB);
}
}
}
case AsPattern as ap: {
lowerPatternTest(cx, ap.pattern, value, failB);
}
case BindingPattern as bp: {
lowerPatternTest(cx, bp.pattern, value, failB);
}
case LiteralPattern as lp: {
lowerPatternTest(cx, lp.value, value, failB);
}
case ClassPattern as cp: {
let ct = cx.substitutedNodeType(cp.name);
if (ct is InterfaceType && cp.properties.length == 0) {
// `case Iterable<i32>:` names an interface instantiation.
lowerNamedTypeTest(cx, ct, value, failB);
return;
}
if (!(ct is ClassType)) {
bail(cx, 'untyped class pattern');
}
let st = classStructOf(cx, ct as ClassType);
emitRefTest(cx, value, st, failB);
let castVt = new ValTypeRef(st) as ValType;
var casted = -1;
for (let prop in cp.properties) {
// Streaming parity on both filters: irrefutable property
// patterns contribute no test, and properties without a
// physical struct field are skipped.
if (patternRefutable(cx, prop.value)) {
let fieldIdx = st.fieldIndexByName(prop.name.name);
if (fieldIdx >= 0) {
if (casted < 0) {
casted = cx.b.emit(IrOp.ref_cast, castVt, value,
cx.b.internType(castVt));
}
let fieldRef = cx.b.addRef(new IrRefField(st, prop.name.name));
let fieldVal = cx.b.emit(
IrOp.struct_get, st.fields[fieldIdx].type, casted, fieldRef);
lowerPatternTest(cx, prop.value, fieldVal, failB);
}
}
}
}
case LogicalPattern as lp: {
if (lp.operator == "||") {
if (patternBinds(cx, lp.left) || patternBinds(cx, lp.right)) {
// Both sides bind the same symbols (checker-enforced); each
// side's values merge into the arm through block params.
let syms = new Array<SymbolId>();
collectPatternBindSyms(cx, lp.left, syms);
let tryRight = cx.b.newBlock();
lowerPatternTest(cx, lp.left, value, tryRight);
lowerPatternBindings(cx, lp.left, value);
// Params are added after the left side binds, so the
// symbols' binding types are registered for addParams.
let successB = cx.b.newBlock();
let successParams = cx.addParams(successB, syms);
cx.b.br(successB, cx.envValues(syms));
cx.b.switchTo(tryRight);
lowerPatternTest(cx, lp.right, value, failB);
lowerPatternBindings(cx, lp.right, value);
cx.b.br(successB, cx.envValues(syms));
cx.b.switchTo(successB);
cx.applyParams(syms, successParams);
} else if (patternRefutable(cx, lp.left) &&
patternRefutable(cx, lp.right)) {
let tryRight = cx.b.newBlock();
let successB = cx.b.newBlock();
lowerPatternTest(cx, lp.left, value, tryRight);
cx.b.br(successB, noValues());
cx.b.switchTo(tryRight);
lowerPatternTest(cx, lp.right, value, failB);
cx.b.br(successB, noValues());
cx.b.switchTo(successB);
}
// Otherwise one side always matches, so the whole pattern does.
} else {
lowerPatternTest(cx, lp.left, value, failB);
lowerPatternTest(cx, lp.right, value, failB);
}
}
case NumberLiteral as num: {
let vt = cx.valueTypeOf(value);
if (isRefValType(vt)) {
lowerBigIntPatternTest(cx, value, num, failB);
} else {
var cond = -1;
if (vt is ValTypeI32) {
if (let (true, parsed) = parseI64OrU64Literal(num.raw)) {
let lit = cx.b.constI32(parsed as i32, vt);
cond = cx.b.binary(IrOp.i32_eq, new ValTypeI32(), value, lit);
} else {
bail(cx, 'unparseable pattern literal');
}
} else if (vt is ValTypeI64) {
if (let (true, parsed) = parseI64OrU64Literal(num.raw)) {
let lit = cx.b.constI64(parsed, vt);
cond = cx.b.binary(IrOp.i64_eq, new ValTypeI32(), value, lit);
} else {
bail(cx, 'unparseable pattern literal');
}
} else if (vt is ValTypeF64) {
let lit = cx.b.constF64(parseFloatLiteral(num.raw), vt);
cond = cx.b.binary(IrOp.f64_eq, new ValTypeI32(), value, lit);
} else if (vt is ValTypeF32) {
let lit = cx.b.constF32(parseFloatLiteral(num.raw), vt);
cond = cx.b.binary(IrOp.f32_eq, new ValTypeI32(), value, lit);
} else {
bail(cx, 'number pattern operand');
}
branchUnless(cx, cond, failB);
}
}
case BooleanLiteral as bl: {
let vt = cx.valueTypeOf(value);
if (!(vt is ValTypeI32)) {
bail(cx, 'boolean pattern operand');
}
let lit = cx.b.constI32(if (bl.value) 1 else 0, vt);
let cond = cx.b.binary(IrOp.i32_eq, new ValTypeI32(), value, lit);
branchUnless(cx, cond, failB);
}
case NullLiteral: {
let vt = cx.valueTypeOf(value);
let nullable = vt is ValTypeRefNull || vt is ValTypeAnyRef ||
vt is ValTypeEqRef;
if (!nullable) {
bail(cx, 'null pattern operand');
}
let cond = cx.b.emit(IrOp.ref_is_null, new ValTypeI32(), value, -1);
branchUnless(cx, cond, failB);
}
case StringLiteral as sl: {
let cond = stringPatternEq(cx, value, sl, failB);
branchUnless(cx, cond, failB);
}
case MemberExpression as me: {
// Enum constants and other member reads: compare by value.
let expected = lowerExpr(cx, me as Expression, null);
let vt = cx.valueTypeOf(value);
if (!valTypeEquals(vt, cx.valueTypeOf(expected))) {
bail(cx, 'member pattern type');
}
var op = IrOp.i32_eq;
if (vt is ValTypeI32) {
op = IrOp.i32_eq;
} else if (vt is ValTypeI64) {
op = IrOp.i64_eq;
} else if (vt is ValTypeF32) {
op = IrOp.f32_eq;
} else if (vt is ValTypeF64) {
op = IrOp.f64_eq;
} else {
bail(cx, 'member pattern operand');
}
let cond = cx.b.binary(op, new ValTypeI32(), value, expected);
branchUnless(cx, cond, failB);
}
case TuplePattern as tp: {
let laneNodes = new Array<Node | null>();
let lanes = if (tupleRestIndexOf(tp) < 0) unionTupleLanes(cx, tp, value, laneNodes) else null;
if (lanes != null) {
for (var i = 0; i < laneNodes.length; i += 1) {
let el = laneNodes[i];
if (el != null && patternRefutable(cx, el)) {
lowerPatternTest(cx, el, lanes[i], failB);
}
}
return;
}
// Elements after a `...rest` count from the tuple's end.
let restIndex = tupleRestIndexOf(tp);
let count = tp.elements.length;
let length = if (restIndex >= 0) structOfValue(cx, value).fields.length else count;
for (var i = 0; i < count; i += 1) {
let el = tp.elements[i];
if (el != null && i != restIndex && patternRefutable(cx, el)) {
let at = if (restIndex < 0 || i < restIndex) i else length - (count - i);
let fieldVal = tupleFieldRead(cx, value, at);
lowerPatternTest(cx, el, fieldVal, failB);
}
}
}
case ArrayPattern as ap: {
var minLen = 0;
var hasRest = false;
for (let el in ap.elements) {
if (el is RestPattern) {
hasRest = true;
break;
}
minLen += 1;
}
let len = arrayLengthRead(cx, value);
let minLenVal = cx.b.constI32(minLen, new ValTypeI32());
let op = if (hasRest) IrOp.i32_ge_s else IrOp.i32_eq;
let cond = cx.b.binary(op, new ValTypeI32(), len, minLenVal);
branchUnless(cx, cond, failB);
for (var i = 0; i < ap.elements.length; i += 1) {
let el = ap.elements[i];
if (el != null) {
if (el is RestPattern) {
let restPat = (el as RestPattern).pattern;
if (patternRefutable(cx, restPat)) {
let sliceVal = arraySliceRead(cx, value, i);
lowerPatternTest(cx, restPat, sliceVal, failB);
}
} else if (patternRefutable(cx, el)) {
let elemVal = arrayElementRead(cx, value, i);
lowerPatternTest(cx, el, elemVal, failB);
}
}
}
}
case RestPattern as rp: {
lowerPatternTest(cx, rp.pattern, value, failB);
}
case RecordPattern as rp: {
let recordValue = recordPatternValue(cx, rp, value);
let dispatchOpt = recordDispatchOfValue(cx, recordValue);
if (dispatchOpt == null) {
bail(cx, 'record pattern operand');
}
let dispatch = dispatchOpt as RecordDispatchInfo;
for (let prop in rp.properties) {
let bit = dispatch.optionalBitOf(prop.name.name);
if (prop.value is AbsencePattern) {
// `{!field}` — matches when the presence bit is CLEAR. The
// checker guarantees the field is optional here.
if (bit < 0) {
bail(cx, 'absence pattern on required field');
}
let present = maskBitTest(cx, dispatch, bit, recordValue);
let absent = cx.b.emit(IrOp.i32_eqz,
new ValTypeI32() as ValType, present, -1);
branchUnless(cx, absent, failB);
continue;
}
// Naming an optional field without a default asserts its
// presence: test the mask bit before any value test. (Repeated
// word reads deduplicate in GVN.)
if (bit >= 0 && !(prop.value is AssignmentPattern)) {
branchUnless(cx, maskBitTest(cx, dispatch, bit, recordValue), failB);
}
if (patternRefutable(cx, prop.value)) {
let read = cx.recordDispatchRead(
dispatch, prop.name.name, recordValue);
lowerPatternTest(cx, prop.value, read, failB);
}
}
}
case AssignmentPattern as ap: {
lowerPatternTest(cx, ap.left, value, failB);
}
case _: {
bail(cx, 'pattern kind');
}
}
};
/** Binds `pattern`'s variables against `value` in the current block. */
export let lowerPatternBindings = (cx: LoweringContext, pattern: Node,
value: i32): void => {
match (pattern) {
case IdentifierPattern as pat: {
if (pat.name != "_") {
let sym = cx.func.model.resolveDeclaration(pat);
if (sym != null) {
cx.bindPatternSym(sym, value);
}
}
}
case Identifier as ident: {
if (ident.name != "_") {
let sym = cx.func.model.resolveDeclaration(ident);
if (sym != null && !sym.isType()) {
cx.bindPatternSym(sym, value);
}
}
}
case AsPattern as ap: {
let sym = cx.func.model.resolveDeclaration(ap.name);
if (sym != null) {
cx.bindPatternSym(sym, value);
}
lowerPatternBindings(cx, ap.pattern, value);
}
case BindingPattern as bp: {
lowerPatternBindings(cx, bp.pattern, value);
}
case ClassPattern as cp: {
let ct = cx.substitutedNodeType(cp.name);
if (ct is InterfaceType && cp.properties.length == 0) {
// `case Iterable<i32>:` binds nothing.
return;
}
if (!(ct is ClassType)) {
bail(cx, 'untyped class pattern');
}
let st = classStructOf(cx, ct as ClassType);
let castVt = new ValTypeRef(st) as ValType;
var casted = -1;
for (let prop in cp.properties) {
if (patternBinds(cx, prop.value)) {
let fieldIdx = st.fieldIndexByName(prop.name.name);
if (fieldIdx >= 0) {
if (casted < 0) {
casted = cx.b.emit(IrOp.ref_cast, castVt, value,
cx.b.internType(castVt));
}
let fieldRef = cx.b.addRef(new IrRefField(st, prop.name.name));
let fieldVal = cx.b.emit(
IrOp.struct_get, st.fields[fieldIdx].type, casted, fieldRef);
lowerPatternBindings(cx, prop.value, fieldVal);
}
}
}
}
case LogicalPattern as lp: {
if (lp.operator != "||") {
lowerPatternBindings(cx, lp.left, value);
lowerPatternBindings(cx, lp.right, value);
}
// Or-pattern bindings were merged during the test phase.
}
case TuplePattern as tp: {
if (tupleRestIndexOf(tp) >= 0) {
bindTupleWithRest(cx, tp, value);
return;
}
let laneNodes = new Array<Node | null>();
let lanes = unionTupleLanes(cx, tp, value, laneNodes);
if (lanes != null) {
for (var i = 0; i < laneNodes.length; i += 1) {
let el = laneNodes[i];
if (el != null && patternBinds(cx, el)) {
lowerPatternBindings(cx, el, lanes[i]);
}
}
return;
}
for (var i = 0; i < tp.elements.length; i += 1) {
let el = tp.elements[i];
if (el != null && patternBinds(cx, el)) {
lowerPatternBindings(cx, el, tupleFieldRead(cx, value, i));
}
}
}
case ArrayPattern as ap: {
for (var i = 0; i < ap.elements.length; i += 1) {
let el = ap.elements[i];
if (el != null && patternBinds(cx, el)) {
if (el is RestPattern) {
lowerPatternBindings(cx, (el as RestPattern).pattern, arraySliceRead(cx, value, i));
} else {
lowerPatternBindings(cx, el, arrayElementRead(cx, value, i));
}
}
}
}
case RestPattern as rp: {
lowerPatternBindings(cx, rp.pattern, value);
}
case RecordPattern as rp: {
let recordValue = recordPatternValue(cx, rp, value);
let dispatchOpt = recordDispatchOfValue(cx, recordValue);
let tOpt = cx.func.model.getNodeType(rp);
let recOpt: RecordType | null =
if (tOpt is RecordType) tOpt else null;
for (let prop in rp.properties) {
if (patternBinds(cx, prop.value)) {
if (dispatchOpt != null) {
bindRecordProp(cx, dispatchOpt, recOpt, prop, recordValue);
} else {
let read = cx.objectPropertyRead(prop.name.name, recordValue);
lowerPatternBindings(cx, prop.value, read);
}
}
}
let rest = rp.rest;
if (rest != null && patternBinds(cx, rest)) {
lowerPatternBindings(cx, rest, recordRestValue(cx, rest, recordValue));
}
}
case AssignmentPattern as ap: {
// `{x = 0}` on a REQUIRED field — the field is always present,
// so the default never applies and the left pattern binds the
// field value directly. (Optional fields route through
// bindRecordProp, which guards on the presence bit.)
lowerPatternBindings(cx, ap.left, value);
}
case _: {}
}
};
/**
* An i32 0/1 condition for "optional field `bit` is present": reads
* the record's presence word for that bit and extracts it.
*/
export let maskBitTest = (cx: LoweringContext, dispatch: RecordDispatchInfo,
bit: i32, receiver: i32): i32 => {
let i64Vt: ValType = new ValTypeI64();
let mask = cx.recordDispatchRead(
dispatch, presentWordName(bit >> 6), receiver);
let bitVal = cx.b.binary(IrOp.i64_and, i64Vt,
cx.b.binary(IrOp.i64_shr_u, i64Vt, mask,
cx.b.constI64((bit & 63) as i64, i64Vt)),
cx.b.constI64(1, i64Vt));
return cx.b.emit(IrOp.i32_wrap_i64,
new ValTypeI32() as ValType, bitVal, -1);
};
/** Whether a record property's Zena type itself admits null (as opposed
* to its slot being nullable only because the field is optional). */
export let propTypeAdmitsNull = (rec: RecordType | null, name: String): boolean => {
if (rec == null) { return true; }
if (!rec.properties.has(name)) { return true; }
let bt = unwrapAliases(rec.properties[name]);
return match (bt) {
case NullType: true
case UnionType {types}: {
var admits = false;
for (let m in types) {
if (m is NullType) { admits = true; }
}
admits
}
case _: false
};
};
/**
* Binds one record-pattern property against a dispatch-carried record
* value. Required fields read and bind directly. An optional field
* with a default (`{x = d}`) branches on its presence bit — slot value
* when present, the default expression when absent. An optional field
* without a default relies on the presence test the refutable phase
* already ran; the slot holds the value, re-asserted non-null when the
* slot is nullable only because the field is optional.
*/
export let bindRecordProp = (cx: LoweringContext,
dispatch: RecordDispatchInfo, rec: RecordType | null,
prop: BindingProperty, receiver: i32): void => {
let {name} = prop.name;
let bit = dispatch.optionalBitOf(name);
if (bit < 0) {
let read = cx.recordDispatchRead(dispatch, name, receiver);
lowerPatternBindings(cx, prop.value, read);
return;
}
if (prop.value is AssignmentPattern) {
let ap = prop.value as AssignmentPattern;
let leftSym = cx.func.model.resolveDeclaration(ap.left);
if (leftSym == null) {
bail(cx, 'optional destructuring default shape');
}
let btOpt = cx.func.model.getBindingType(leftSym as Symbol);
if (btOpt == null) {
bail(cx, 'untyped optional destructuring default');
}
let targetVt = typeToValTypeWithSub(cx.wasm, btOpt as Type, cx.func);
let bitVal = maskBitTest(cx, dispatch, bit, receiver);
let presentB = cx.b.newBlock();
let absentB = cx.b.newBlock();
let merge = cx.b.newBlock();
let bound = cx.b.blockParam(merge, targetVt);
cx.b.brIf(bitVal, presentB, noValues(), absentB, noValues());
cx.b.switchTo(presentB);
let slotVal = cx.recordDispatchRead(dispatch, name, receiver);
cx.b.br(merge, oneValue(cx.coerceTo(slotVal, targetVt)));
cx.b.switchTo(absentB);
let defVal = lowerExpr(cx, ap.right, null);
cx.b.br(merge, oneValue(cx.coerceTo(defVal, targetVt)));
cx.b.switchTo(merge);
lowerPatternBindings(cx, ap.left, bound);
return;
}
var read = cx.recordDispatchRead(dispatch, name, receiver);
let rv = cx.valueTypeOf(read);
if (rv is ValTypeRefNull && !propTypeAdmitsNull(rec, name)) {
read = cx.reassertNonNull(read,
new ValTypeRef((rv as ValTypeRefNull).target) as ValType);
}
lowerPatternBindings(cx, prop.value, read);
};
- 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 |
|
|