/**
* 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
(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, '');
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();
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(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(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([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('', loc));
}
if (bt is TupleType || bt is InlineTupleType) {
return lowerStringLiteral(cx, new StringLiteral('', loc));
}
if (tOpt is NullType) {
return lowerStringLiteral(cx, new StringLiteral('null', loc));
}
return lowerStringLiteral(cx, new StringLiteral('