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
23.1 KiB
Raw
/**
* String literal, template literal, and tagged-template lowering,
* split out of lowering.zena. Each function takes the shared LoweringContext;
* bodies are streaming's shapes exactly (see the per-function docs).
*/
import {
Expression, Identifier, SourceLocation, StringLiteral, TaggedTemplateExpression,
TemplateLiteral,
} from '../../ast.zena';
import {
AnyRefType, ArrayType, ClassType, FunctionType, InlineTupleType, InterfaceType,
NullType, RecordType, TupleType, Type, UnionType, baseType,
} from '../../types.zena';
import { Symbol } from '../../scope/symbol.zena';
import {
ValType, ValTypeAnyRef, ValTypeEqRef, ValTypeI32, ValTypeI64, ValTypeRef, ValTypeRefNull,
ValTypeStructRef,
} from '../wasm.zena';
import {
ClassCodegenInfo, WasmFunction, WasmGlobal, WasmSignature, WasmStruct,
asWasmSignature, asWasmStruct, isValSubtype,
} from '../wasm-module.zena';
import { bigIntLiteralCacheKey, getClassKey, getClassMethodKey, parseBigIntLiteralLimbs, templateConvertHelperName } from '../codegen-utils.zena';
import {
eraseTypeParameters, findExtendedWellKnownInterface, findImplementedWellKnownInterface,
getNonNullableType, substituteTypeParamsInFunctionContext, typeToValTypeWithSub,
} from '../type-mapping.zena';
import { IrOp, IrRefField, IrRefFunc, IrRefGlobal, IrRefType } from './ir.zena';
import { lowerExpr } from './lowering.zena';
import {
LoweringContext, noValues, oneValue, twoValues,
} from './lowering-context.zena';
import { WellKnown, isWellKnown } from '../../well-known.zena';
import { growable } from 'zena:core';
import { targetUsesJsStrings } from '../../targets.zena';
/**
* A primitive interpolation the checker boxed for its tag
* (`SemanticModel.getBoxAdaptation`): the value, then the box class's
* constructor around it — `new Box<P>(value)` with the class resolved
* in this function's context.
*/
function lowerBoxedTemplateValue(cx: LoweringContext, sub: Expression, box: ClassType): i32 {
let resolved = eraseTypeParameters(cx.wasm,
substituteTypeParamsInFunctionContext(cx.wasm, cx.func, box));
if (!(resolved is ClassType)) {
cx.fail('boxed interpolation class');
}
let cKey = getClassKey(resolved);
let ctorKey = getClassMethodKey(cKey, '<constructor>');
let ctor = if (let (true, c) = cx.wasm.classMethodMap.get(ctorKey)) c else null;
if (ctor == null) {
cx.fail('boxed interpolation constructor');
}
let sig = ctor.signature;
if (sig.params.length != 1 || sig.returns.length != 1) {
cx.fail('boxed interpolation constructor shape');
}
let valueVt = sig.params[0];
let value = lowerExpr(cx, sub, valueVt);
if (!isValSubtype(cx.valueTypeOf(value), valueVt)) {
cx.failConformance(value, valueVt, 'boxed interpolation value');
}
let args = new Array<i32>();
args.push(value);
return cx.b.callFunc(cx.b.addRef(new IrRefFunc(ctor)), args, sig.returns[0]);
}
/**
* A string literal: id lookup in the shared registry, then the
* get_string_literal helper call. Same contract as streaming: the
* registry is complete by construction, so a miss is a discovery bug
* — a plain Error (not ZirUnsupported) fails the compile loudly
* rather than falling back to a second storage story.
*/
export function lowerStringLiteral(cx: LoweringContext, lit: StringLiteral): i32 {
if (targetUsesJsStrings(cx.wasm.target)) {
let gw = cx.wasm.getImportedStringWrapperGlobal(lit.value, cx.func.model);
let ref = cx.b.addRef(new IrRefGlobal(gw));
let get = cx.b.emit(IrOp.global_get, gw.type, -1, ref);
let sKey = getClassKey(cx.wasm.stringClass as ClassType);
let info = cx.wasm.classInfos[sKey];
let nonNullVt = new ValTypeRef(info.structType) as ValType;
return cx.b.emit(IrOp.ref_as_non_null, nonNullVt, get, -1);
}
let litId = if (let (true, id) = cx.wasm.stringLiteralIds.get(lit.value)) id else -1;
if (litId < 0) {
throw new Error("String literal missing from the shared registry: '" +
lit.value + "'");
}
if (cx.wasm.getStringLiteralFunc == null) {
cx.fail('no string literal helper');
}
let helper = cx.wasm.getStringLiteralFunc as WasmFunction;
if (helper.signature.returns.length != 1) {
cx.fail('string helper shape');
}
let id = cx.b.constI32(litId, new ValTypeI32());
let funcRef = cx.b.addRef(new IrRefFunc(helper));
let call = cx.b.callFunc(funcRef, oneValue(id), helper.signature.returns[0]);
// The literal is a non-null String; the helper returns nullable.
// Re-assert so merges and returns type-check. Synthesized quasi
// literals (template parts) carry no checker type — strip via the
// value's own type instead.
if (cx.func.model.getNodeType(lit) == null) {
return cx.stripNonNull(call);
}
return cx.reassertNonNull(call, cx.exprVt(lit));
}
/**
* A `BigInt` literal (either `42n` or an integer literal contextually typed
* as `BigInt`): loads the pre-registered cache global, and on first evaluation
* materializes its compile-time `(sign, limbs)` array via `BigInt.#fromMag`
* and caches the instance in the global.
*/
export function lowerBigIntLiteral(cx: LoweringContext, raw: String,
negative: boolean): i32 {
let bcOpt = cx.wasm.bigIntClass;
if (bcOpt == null) {
cx.fail('bigint class missing');
}
let bc = bcOpt;
let cKey = getClassKey(bc);
let infoOpt = if (let (true, info) = cx.wasm.classInfos.get(cKey)) info else null;
if (infoOpt == null) {
cx.fail('bigint struct missing');
}
let bigIntStruct = infoOpt.structType;
let (sign, limbs) = parseBigIntLiteralLimbs(raw, negative);
let cacheKey = bigIntLiteralCacheKey(sign, limbs);
let gOpt = if (let (true, g) = cx.wasm.bigIntLiteralGlobals.get(cacheKey)) g else null;
if (gOpt == null) {
cx.fail('bigint literal global missing');
}
let g = gOpt;
let fromMagKey = getClassMethodKey(cKey, '#fromMag');
let fromMagOpt = if (let (true, f) = cx.wasm.staticMethodMap.get(fromMagKey)) f else null;
if (fromMagOpt == null) {
cx.fail('BigInt.#fromMag missing');
}
let fromMag = fromMagOpt;
if (fromMag.signature.params.length != 2 || fromMag.signature.returns.length != 1) {
cx.fail('BigInt.#fromMag shape');
}
let globalRef = cx.b.addRef(new IrRefGlobal(g));
let cached = cx.b.emit(IrOp.global_get, g.type, -1, globalRef);
let isNull = cx.b.emit(IrOp.ref_is_null, new ValTypeI32(), cached, -1);
let initB = cx.b.newBlock();
let doneB = cx.b.newBlock();
cx.b.brIf(isNull, initB, noValues(), doneB, noValues());
cx.b.switchTo(initB);
let u64Arr = cx.wasm.getArray(new ValTypeI64() as ValType, true);
let limbIds = new Array<i32>(limbs.length);
let i64Vt = new ValTypeI64() as ValType;
for (var i = 0; i < limbs.length; i += 1) {
limbIds.push(cx.b.constI64(limbs[i] as i64, i64Vt));
}
let arrVal = cx.b.emit(IrOp.array_new_fixed,
new ValTypeRef(u64Arr) as ValType,
cx.b.pushArgList(limbIds),
cx.b.addRef(new IrRefType(u64Arr)));
let signVal = cx.b.constI32(sign, new ValTypeI32());
let limbsArg = cx.coerceTo(arrVal, fromMag.signature.params[1]);
let created = cx.b.callFunc(cx.b.addRef(new IrRefFunc(fromMag)),
twoValues(signVal, limbsArg), fromMag.signature.returns[0]);
let stored = cx.coerceTo(created, g.type);
cx.b.emitVoid(IrOp.global_set, stored, globalRef);
cx.b.br(doneB, noValues());
cx.b.switchTo(doneB);
let loaded = cx.b.emit(IrOp.global_get, g.type, -1, globalRef);
return cx.b.emit(IrOp.ref_as_non_null,
new ValTypeRef(bigIntStruct) as ValType, loaded, -1);
}
/**
* Template literals: quasi/expression parts in order, primitives
* converted through the zena:string-convert helpers, then joined —
* __concatN for 2..5 parts, else array.new_fixed + String.fromRawParts
* (streaming's shape exactly).
*/
export function lowerTemplateLiteral(cx: LoweringContext, tpl: TemplateLiteral): i32 {
if (tpl.quasis.length + tpl.expressions.length == 0) {
return lowerStringLiteral(cx, new StringLiteral('', tpl.loc));
}
if (tpl.expressions.length == 0) {
return lowerStringLiteral(cx,
new StringLiteral(tpl.quasis[0].cooked, tpl.loc));
}
let parts = new Array<i32>(tpl.expressions.length);
for (var i = 0; i < tpl.expressions.length; i += 1) {
parts.push(lowerStringLiteral(cx,
new StringLiteral(tpl.quasis[i].cooked, tpl.quasis[i].loc)));
parts.push(templateOperandString(cx, tpl.expressions[i]));
}
parts.push(lowerStringLiteral(cx, new StringLiteral(
tpl.quasis[tpl.quasis.length - 1].cooked,
tpl.quasis[tpl.quasis.length - 1].loc)));
if (parts.length >= 2 && parts.length <= 5) {
let concat = cx.wasm.getStdlibFunc(
'core', '__concat' + i32ToString(parts.length));
if (concat != null) {
let sig = concat.signature;
if (sig.returns.length != 1 || sig.params.length != parts.length) {
cx.fail('concat helper shape');
}
for (var i = 0; i < parts.length; i += 1) {
parts[i] = cx.coerceTo(parts[i], sig.params[i]);
}
let call = cx.b.callFunc(
cx.b.addRef(new IrRefFunc(concat)), parts, sig.returns[0]);
return cx.reassertNonNull(call, cx.exprVt(tpl as Expression));
}
}
// fromRawParts is the concrete raw-array entry; the public fromParts
// is generic over the array representation and has no single
// signature to call by name.
let fromPartsOpt = if (cx.wasm.stringClass != null) {
let key = getClassMethodKey(
getClassKey(cx.wasm.stringClass as ClassType), 'fromRawParts');
if (let (true, f) = cx.wasm.staticMethodMap.get(key)) f else null
} else {
null
};
if (fromPartsOpt == null) {
cx.fail('String.fromRawParts missing');
}
let fromParts = fromPartsOpt;
let fsig = fromParts.signature;
if (fsig.returns.length != 1 || fsig.params.length != 1) {
cx.fail('fromParts shape');
}
let elemVt = if (parts.length > 0) {
match (cx.valueTypeOf(parts[0])) {
case ValTypeRef as r: new ValTypeRefNull(r.target) as ValType
case _: cx.valueTypeOf(parts[0])
}
} else {
new ValTypeI32() as ValType
};
let arr = cx.wasm.getArray(elemVt, true);
let arrValue = cx.b.emit(IrOp.array_new_fixed,
new ValTypeRef(arr) as ValType,
cx.b.pushArgList(parts), cx.b.addRef(new IrRefType(arr)));
if (!isValSubtype(cx.valueTypeOf(arrValue), fsig.params[0])) {
cx.fail('fromParts operand type');
}
let args = growable<i32>([arrValue]);
let call = cx.b.callFunc(
cx.b.addRef(new IrRefFunc(fromParts)), args, fsig.returns[0]);
return cx.reassertNonNull(call, cx.exprVt(tpl as Expression));
}
function isNullableRef(vt: ValType): boolean {
return match (vt) {
case ValTypeRefNull: true
case ValTypeAnyRef: true
case ValTypeEqRef: true
case ValTypeStructRef: true
case _: false
};
}
function callUnaryToString(cx: LoweringContext, fn: WasmFunction, v: i32) {
if (fn.signature.params.length != 1 || fn.signature.returns.length != 1) {
cx.fail('unary method shape');
}
let recv = cx.coerceTo(v, fn.signature.params[0]);
let funcRef = cx.b.addRef(new IrRefFunc(fn));
return cx.b.callFunc(funcRef, oneValue(recv), fn.signature.returns[0]);
}
function convertClassToString(cx: LoweringContext, value: i32, ct: ClassType, loc: SourceLocation | null) {
if (isWellKnown(WellKnown.StringClass, ct.name, ct.sourcePath)) {
return value;
}
let stringableIface = findImplementedWellKnownInterface(cx.wasm, ct, WellKnown.StringableInterface);
if (stringableIface != null) {
let toStringMethod = cx.resolveDevirtualizedMethod(ct, ':toString');
if (toStringMethod != null) {
return callUnaryToString(cx, toStringMethod, value);
}
var resolvedOpt: WasmFunction | null = null;
var hc: ClassType | null = ct;
while (hc != null && resolvedOpt == null) {
var hg: ClassType | null = hc;
while (hg != null && resolvedOpt == null) {
let key = getClassMethodKey(getClassKey(hg), ':toString');
if (let (true, m) = cx.wasm.classMethodMap.get(key)) {
resolvedOpt = m;
}
hg = hg.genericSource;
}
hc = hc.superType;
}
let ci = if (let (true, info) = cx.wasm.classInfos.get(getClassKey(ct))) info else null;
if (resolvedOpt != null && ci != null && cx.vtableSlotIndex(ci, ':toString') >= 0) {
let hsig = resolvedOpt.signature;
return cx.lowerVtableCall(value, ci, ':toString', hsig,
oneValue(value), hsig.returns[0]);
}
}
return lowerStringLiteral(cx, new StringLiteral(`<${ct.name}>`, loc));
}
function convertNonNullValueToString(cx: LoweringContext, value: i32, tOpt: Type, loc: SourceLocation | null) {
let bt = baseType(tOpt);
let helperName = templateConvertHelperName(tOpt);
if (helperName != '') {
let helperOpt = cx.wasm.getStdlibFunc('core', helperName);
if (helperOpt == null) {
cx.fail('template helper missing: ' + helperName);
}
let helper = helperOpt;
let sig = helper.signature;
if (sig.params.length != 1 || sig.returns.length != 1) {
cx.fail('template helper shape');
}
if (!isValSubtype(cx.valueTypeOf(value), sig.params[0])) {
cx.failConformance(value, sig.params[0], 'template operand type');
}
return cx.b.callFunc(
cx.b.addRef(new IrRefFunc(helper)), oneValue(value), sig.returns[0]);
}
if (bt is ClassType) {
return convertClassToString(cx, value, bt, loc);
}
if (bt is InterfaceType) {
let stringableIface = findExtendedWellKnownInterface(cx.wasm, bt, WellKnown.StringableInterface);
if (stringableIface != null) {
return cx.slotCallSingle(value, ':toString');
}
return lowerStringLiteral(cx, new StringLiteral(`<${bt.name}>`, loc));
}
if (bt is RecordType) {
return lowerStringLiteral(cx, new StringLiteral('<record>', loc));
}
if (bt is TupleType || bt is InlineTupleType) {
return lowerStringLiteral(cx, new StringLiteral('<tuple>', loc));
}
if (tOpt is NullType) {
return lowerStringLiteral(cx, new StringLiteral('null', loc));
}
return lowerStringLiteral(cx, new StringLiteral('<object>', loc));
}
function typeHasNull(t: Type): boolean {
return match (t) {
case NullType: true
case UnionType {types}: {
var found = false;
for (let m in types) {
if (m is NullType) {
found = true;
}
}
found
}
case _: false
};
}
/**
* Converts any value to a String. Used by template literals and the to_string intrinsic.
*/
export function convertValueToString(cx: LoweringContext, value: i32, tOpt: Type, loc: SourceLocation | null): i32 {
if (tOpt is NullType) {
return lowerStringLiteral(cx, new StringLiteral('null', loc));
}
let valVt = cx.valueTypeOf(value);
let nonNullT = getNonNullableType(tOpt);
if (typeHasNull(tOpt) && isNullableRef(valVt)) {
let isNull = cx.b.emit(IrOp.ref_is_null, new ValTypeI32() as ValType, value, -1);
let nullB = cx.b.newBlock();
let nonNullB = cx.b.newBlock();
cx.b.brIf(isNull, nullB, noValues(), nonNullB, noValues());
cx.b.switchTo(nullB);
let nullStr = lowerStringLiteral(cx, new StringLiteral('null', loc));
let strVt = cx.valueTypeOf(nullStr);
let mergeB = cx.b.newBlock();
let result = cx.b.blockParam(mergeB, strVt);
cx.b.br(mergeB, oneValue(nullStr));
cx.b.switchTo(nonNullB);
let nonNullVal = cx.stripNonNull(value);
let converted = cx.stripNonNull(convertNonNullValueToString(cx, nonNullVal, nonNullT, loc));
cx.b.br(mergeB, oneValue(converted));
cx.b.switchTo(mergeB);
return result;
}
return convertNonNullValueToString(cx, value, nonNullT, loc);
}
/**
* A template interpolation as a String value: delegates to convertValueToString.
*/
function templateOperandString(cx: LoweringContext, expr: Expression): i32 {
let value = lowerExpr(cx, expr, null);
let tOpt = cx.substitutedNodeType(expr);
if (tOpt == null) {
cx.fail('untyped template operand');
}
return convertValueToString(cx, value, tOpt, expr.loc);
}
/**
* Tagged templates: the TemplateStringsArray is built once and
* cached in the expression's pre-registered global (discovery
* created it); the interpolated values become a FixedArray typed by
* the tag's second parameter; then the tag is called — directly for
* top-level functions, through the closure pair for local values.
* Streaming's shape throughout, including the lazy-init null check.
*/
export function lowerTaggedTemplate(cx: LoweringContext,
expr: TaggedTemplateExpression): i32 {
let tsaClassOpt = cx.wasm.templateStringsArrayClass;
if (tsaClassOpt == null) {
cx.fail('template strings array class missing');
}
let tsaKey = getClassKey(tsaClassOpt);
let tsaInfoOpt = if (let (true, info) = cx.wasm.classInfos.get(tsaKey)) info else null;
if (tsaInfoOpt == null) {
cx.fail('template strings array struct missing');
}
let tsaInfo = tsaInfoOpt;
let tsaStruct = tsaInfo.structType;
let stringClassOpt = cx.wasm.stringClass;
if (stringClassOpt == null) {
cx.fail('string class missing');
}
let stringKey = getClassKey(stringClassOpt);
let strInfoOpt = if (let (true, info) = cx.wasm.classInfos.get(stringKey)) info else null;
if (strInfoOpt == null) {
cx.fail('string struct missing');
}
let stringStruct = strInfoOpt.structType;
// TemplateStringsArray's #strings/#raw are ImmutableArray<String>,
// so the constant tables build as `(array (ref null $String))` —
// the immutable form.
let stringsArr = cx.wasm.getArray(
new ValTypeRefNull(stringStruct) as ValType, false);
let gOpt = if (cx.wasm.templateLiteralGlobals.has(expr)) {
cx.wasm.templateLiteralGlobals[expr]
} else {
null
};
if (gOpt == null) {
cx.fail('tagged template global missing');
}
let g = gOpt;
// Lazy init: build the TSA on first evaluation, cache it.
let cached = cx.b.emit(IrOp.global_get, g.type, -1,
cx.b.addRef(new IrRefGlobal(g)));
let isNull = cx.b.emit(IrOp.ref_is_null, new ValTypeI32(), cached, -1);
let initB = cx.b.newBlock();
let doneB = cx.b.newBlock();
cx.b.brIf(isNull, initB, noValues(), doneB, noValues());
cx.b.switchTo(initB);
let cookedParts = new Array<i32>();
for (let quasi in expr.quasi.quasis) {
cookedParts.push(lowerStringLiteral(cx,
new StringLiteral(quasi.cooked, quasi.loc)));
}
let cooked = cx.b.emit(IrOp.array_new_fixed,
new ValTypeRef(stringsArr) as ValType,
cx.b.pushArgList(cookedParts),
cx.b.addRef(new IrRefType(stringsArr)));
let rawParts = new Array<i32>();
for (let quasi in expr.quasi.quasis) {
rawParts.push(lowerStringLiteral(cx,
new StringLiteral(quasi.raw, quasi.loc)));
}
let raw = cx.b.emit(IrOp.array_new_fixed,
new ValTypeRef(stringsArr) as ValType,
cx.b.pushArgList(rawParts),
cx.b.addRef(new IrRefType(stringsArr)));
let tsaArgs = new Array<i32>();
let {vtableGlobal} = tsaInfo;
if (vtableGlobal != null) {
let vtG = vtableGlobal;
tsaArgs.push(cx.b.emit(IrOp.global_get, vtG.type, -1,
cx.b.addRef(new IrRefGlobal(vtG))));
} else {
tsaArgs.push(cx.b.emit(IrOp.ref_null,
tsaStruct.fields[0].type, -1, -1));
}
for (var f = 1; f < tsaStruct.fields.length; f += 1) {
let fieldName = if (tsaStruct.fields[f].name != null) {
tsaStruct.fields[f].name as String
} else {
''
};
if (fieldName.endsWith('::#strings')) {
tsaArgs.push(cooked);
} else if (fieldName.endsWith('::#raw')) {
tsaArgs.push(raw);
} else {
let ft = tsaStruct.fields[f].type;
tsaArgs.push(if (ft is ValTypeI32) {
cx.b.constI32(0, new ValTypeI32())
} else {
cx.b.emit(IrOp.ref_null, ft, -1, -1)
});
}
}
let tsaNew = cx.b.emit(IrOp.struct_new,
new ValTypeRef(tsaStruct) as ValType,
cx.b.pushArgList(tsaArgs),
cx.b.addRef(new IrRefType(tsaStruct)));
cx.b.emitVoid(IrOp.global_set, tsaNew,
cx.b.addRef(new IrRefGlobal(g)));
cx.b.br(doneB, noValues());
cx.b.switchTo(doneB);
let tsaLoaded = cx.b.emit(IrOp.global_get, g.type, -1,
cx.b.addRef(new IrRefGlobal(g)));
let tsa = cx.b.emit(IrOp.ref_as_non_null,
new ValTypeRef(tsaStruct) as ValType, tsaLoaded, -1);
// Interpolated values, typed by the tag's second parameter.
let calleeType = cx.func.model.getNodeType(expr.tag);
var valueType: Type = new AnyRefType();
if (calleeType is FunctionType) {
if (calleeType.parameters.length >= 2) {
let vp = baseType(calleeType.parameters[1]);
if (vp is ClassType) {
let targs = vp.typeArguments;
if (targs != null && targs.length > 0) {
valueType = targs[0];
}
} else if (vp is ArrayType) {
valueType = vp.elementType;
}
}
}
let valVt = typeToValTypeWithSub(cx.wasm, valueType, cx.func);
cx.requireSupported(valVt, 'tagged template value type');
let valuesArr = cx.wasm.getArray(valVt, true);
let valueParts = new Array<i32>();
for (let sub in expr.quasi.expressions) {
let box = cx.func.model.getBoxAdaptation(sub);
let v = if (box != null) {
lowerBoxedTemplateValue(cx, sub, box)
} else {
lowerExpr(cx, sub, valVt)
};
if (!isValSubtype(cx.valueTypeOf(v), valVt)) {
cx.failConformance(v, valVt, 'tagged template value type');
}
valueParts.push(v);
}
let values = cx.b.emit(IrOp.array_new_fixed,
new ValTypeRef(valuesArr) as ValType,
cx.b.pushArgList(valueParts),
cx.b.addRef(new IrRefType(valuesArr)));
// Call the tag.
if (!(expr.tag is Identifier)) {
cx.fail('tagged template tag kind');
}
let symOpt = cx.func.model.resolve(expr.tag);
if (symOpt == null) {
cx.fail('tagged template tag unresolved');
}
let resolved = symOpt.resolveTarget();
let callArgs = twoValues(tsa, values);
if (let (true, target) = cx.wasm.functionMap.get(resolved.id)) {
let sig = target.signature;
if (sig.params.length != 2 || sig.returns.length > 1) {
cx.fail('tagged template tag shape');
}
let resultType = if (sig.returns.length == 1) sig.returns[0] else null;
return cx.b.callFunc(
cx.b.addRef(new IrRefFunc(target)), callArgs, resultType);
}
// A local value: call through its closure pair.
let callee = if (cx.env.has(resolved.id)) cx.env[resolved.id] else -1;
if (callee < 0) {
cx.fail('tagged template tag target');
}
let structOpt = asWasmStruct(cx.valueTypeOf(callee));
if (structOpt == null) {
cx.fail('tagged template tag kind');
}
let closureStruct = structOpt;
if (closureStruct.fields.length != 2) {
cx.fail('tagged template tag kind');
}
let sigOpt = asWasmSignature(closureStruct.fields[0].type);
if (sigOpt == null) {
cx.fail('tagged template tag kind');
}
let csig = sigOpt;
if (csig.params.length != 3 || csig.returns.length > 1) {
cx.fail('tagged template tag shape');
}
let ctxVal = cx.b.emit(IrOp.struct_get, closureStruct.fields[1].type,
callee, cx.b.addRef(new IrRefField(closureStruct, 'ctx')));
let funcVal = cx.b.emit(IrOp.struct_get, closureStruct.fields[0].type,
callee, cx.b.addRef(new IrRefField(closureStruct, 'func')));
let clArgs = growable<i32>([ctxVal, tsa, values]);
for (var i = 1; i < csig.params.length; i += 1) {
if (!isValSubtype(cx.valueTypeOf(clArgs[i]), csig.params[i])) {
cx.failConformance(clArgs[i], csig.params[i],
'tagged template argument type');
}
}
let resultType = if (csig.returns.length == 1) csig.returns[0] else null;
return cx.b.callRef(funcVal, clArgs, resultType);
}
- 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 |
|
|