diff --git a/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md b/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md index 90cc65b7a..4f8842f77 100644 --- a/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md +++ b/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md @@ -5352,3 +5352,29 @@ from a `let` declared in it and from one given anew in it, churning between step none; the ownership verifier is silent on it. `own_err_let_field_{global,read_again,loop,captured}` stay borrows; so do a parameter or a mix of a parameter and a fresh object given to the local, and a `let h = r` read after. + +## 66. An object literal whose arrows capture, given later to an object type, 2026-10-29 + +`const k = 2; const o = { w: (x: number) => x * k }; apply(o)` for `apply(o: { w: (x: number) => +number })` was `'this value' borrows a field and cannot be stored, returned or captured` (spec 62 left +an arrow that names a local around it a method bound to the literal). The cast to the parameter's object +type reads each member out of the literal (`ts.Cast` of the object to its storage, a `ts.PropertyRef` +and a `Load` of each field: a method bound to the literal) and makes the parameter's tuple of them +(`ts.CreateTuple`). The members stay methods; the call borrows them. + +- **The tuple passes the borrow on** (`passesOn`): what the tuple is given to has the bound method, and + is walked as it. A store, a return or a call that keeps the tuple still keeps the borrow. +- **The object is the chain's root** (`chainOf`): a field read through the object seen as its storage + has the object above it, owned when this function made it. Before, the cast was the root, owned by no + one, and so any call - the very call given the tuple - might drop it. +- **Neither moves the object** (`isBorrow`): the cast to its storage when only its fields are reached + through it (each read is a place read, as `o.w` straight off the object is), and a tuple made of a + value only to be given to calls that keep none of it, released by nothing. + +`own_literal_captures` gives such literals (a number captured, a string captured by two members) to an +object-type parameter, calls a member after, gives the literal again and to an interface, churning +between steps, under own, rc, gc and none. + +Not here: a literal whose arrow captures an object (`const b = new Box(5); const q = { w: (x: number) => +x * b.n }`) moves the object into the literal's `.captured`, so `b` cannot be used after it under own, +where a closure capturing it only borrows it (ยง16). diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index f468bee38..e34a5bca4 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -488,7 +488,12 @@ // Fields may be added, but never reordered or resized, and a new one goes immediately before // the block header, which has to stay last - see TYPE_DESCR_BLOCK_HEADER. #define TYPE_DESCR_KIND 0 -#define TYPE_DESCR_RESERVED 1 +// For a tuple, an id of its layout - its fields' names and types (TypeOfOpHelper::layoutIdOf) - +// and 0 for anything else. A cast from `any` to an object type compares it with the type's own +// (ts.IsTupleOfLayout): the box says only "tuple", and a tuple of other fields read as the type's +// was garbage (`{ n: 5 }` holds an s32, read as a number). Computed from the type's text, so a +// tuple boxed by one module matches the same type in another. +#define TYPE_DESCR_LAYOUT 1 // Address of the type's release routine, or null when the type owns no heap memory - null // says "nothing to release", not "unknown". Generated by OwnershipRoutineLogic. #define TYPE_DESCR_RELEASE 2 diff --git a/tslang/include/TypeScript/LowerToLLVM/LLVMCodeHelper.h b/tslang/include/TypeScript/LowerToLLVM/LLVMCodeHelper.h index 04b6a0a4a..507fb1dd8 100644 --- a/tslang/include/TypeScript/LowerToLLVM/LLVMCodeHelper.h +++ b/tslang/include/TypeScript/LowerToLLVM/LLVMCodeHelper.h @@ -354,7 +354,7 @@ class LLVMCodeHelper : public LLVMCodeHelperBase // capture box); it is not part of the name the record carries. mlir::Value getOrCreateTypeDescriptorName(mlir::Type type, std::string name, int kind, StringRef releaseRoutineName, StringRef retainRoutineName, - StringRef variant = "") + StringRef variant = "", uint32_t layout = 0) { auto loc = op->getLoc(); auto parentModule = op->getParentOfType(); @@ -390,8 +390,9 @@ class LLVMCodeHelper : public LLVMCodeHelperBase mlir::Value recordValue = rewriter.create(loc, recordType); setStructValue(loc, recordValue, rewriter.create(loc, i32Ty, rewriter.getI32IntegerAttr(kind)), TYPE_DESCR_KIND); - setStructValue(loc, recordValue, rewriter.create(loc, i32Ty, rewriter.getI32IntegerAttr(0)), - TYPE_DESCR_RESERVED); + setStructValue(loc, recordValue, + rewriter.create(loc, i32Ty, rewriter.getI32IntegerAttr((int32_t)layout)), + TYPE_DESCR_LAYOUT); // empty when the type owns no heap memory, which a null slot states positively: // "nothing to release", rather than leaving it unknown mlir::Value releaseValue = diff --git a/tslang/include/TypeScript/LowerToLLVM/TypeDescriptorLogic.h b/tslang/include/TypeScript/LowerToLLVM/TypeDescriptorLogic.h index 8880578bb..f0273fcc2 100644 --- a/tslang/include/TypeScript/LowerToLLVM/TypeDescriptorLogic.h +++ b/tslang/include/TypeScript/LowerToLLVM/TypeDescriptorLogic.h @@ -32,7 +32,7 @@ class TypeDescriptorLogic { } - // { i32 kind, i32 reserved, ptr release, index blockHeader } + // { i32 kind, i32 layout, ptr release, ptr retain, index blockHeader } static LLVM::LLVMStructType getRecordType(mlir::OpBuilder &builder, mlir::Type llvmIndexType) { auto i32Ty = builder.getI32Type(); @@ -78,6 +78,15 @@ class TypeDescriptorLogic return rewriter.create(loc, th.getI32Type(), kindPtr); } + // TYPE_DESCR_LAYOUT of the type this tag names + mlir::Value getLayoutFromTag(mlir::Value tagValue) + { + auto recordPtr = getRecordPtrFromTag(tagValue); + auto layoutPtr = rewriter.create(loc, th.getPtrType(), getRecordType(), recordPtr, + ArrayRef{0, TYPE_DESCR_LAYOUT}); + return rewriter.create(loc, th.getI32Type(), layoutPtr); + } + mlir::Value isKind(mlir::Value tagValue, int kind) { auto kindValue = getKindFromTag(tagValue); diff --git a/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h b/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h index 785e5b644..1c46a2a74 100644 --- a/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h @@ -8,6 +8,7 @@ #include "TypeScript/TypeScriptOps.h" #include "llvm/ADT/StringSwitch.h" +#include "llvm/Support/xxhash.h" #define DEBUG_TYPE "mlir" @@ -99,6 +100,65 @@ class TypeOfOpHelper .Default(TYPE_KIND_UNKNOWN); } + // A tuple's layout as text: its fields' names and types, with a literal field as its type + // (`{ n: 5 }` holds an s32) and a const tuple as the tuple it is, so a literal and the object + // type that names the same fields read alike. + static void layoutText(mlir::Type type, llvm::raw_ostream &os) + { + if (auto literalType = dyn_cast(type)) + { + layoutText(literalType.getElementType(), os); + return; + } + + llvm::ArrayRef fields; + if (auto tupleType = dyn_cast(type)) + { + fields = tupleType.getFields(); + } + else if (auto constTupleType = dyn_cast(type)) + { + fields = constTupleType.getFields(); + } + else + { + type.print(os); + return; + } + + os << "{"; + for (auto &field : fields) + { + if (field.id) + { + field.id.print(os); + } + + os << ":"; + layoutText(field.type, os); + os << ","; + } + + os << "}"; + } + + // TYPE_DESCR_LAYOUT of a type's descriptor: an id of a tuple's layout text (never 0), and 0 for + // anything else. A hash of the text, not of the type: the type's own hash differs between + // modules, which a tuple boxed in one and cast in another must not. + static uint32_t layoutIdOf(mlir::Type type) + { + if (!isa(type)) + { + return 0; + } + + std::string text; + llvm::raw_string_ostream os(text); + layoutText(type, os); + auto id = (uint32_t)llvm::xxh3_64bits(os.str()); + return id ? id : 1; + } + std::string typeOfAsString(mlir::Type type) { if (type.isIntOrIndex() && !type.isIndex()) diff --git a/tslang/include/TypeScript/TypeScriptOps.td b/tslang/include/TypeScript/TypeScriptOps.td index 6c1fc336e..94baea315 100644 --- a/tslang/include/TypeScript/TypeScriptOps.td +++ b/tslang/include/TypeScript/TypeScriptOps.td @@ -501,6 +501,18 @@ def TypeScript_TypeOfAnyOp : TypeScript_Op<"TypeOfAny", [Pure]> { let results = (outs TypeScript_String:$typeOf); } +def TypeScript_IsTupleOfLayoutOp : TypeScript_Op<"IsTupleOfLayout", [Pure]> { + let summary = "whether an any holds a tuple of a type's layout"; + let description = [{ + True when the box $value holds a tuple whose fields have the names and types of $layoutType's: + the TYPE_DESCR_LAYOUT of the box's tag is $layoutType's. A cast from `any` to an object type + reads the box as that type's layout, which another tuple's is not (`{ n: 5 }` holds an s32). + }]; + + let arguments = (ins TypeScript_Any:$value, TypeAttr:$layoutType); + let results = (outs TypeScript_Boolean:$res); +} + def TypeScript_TypeDescriptorOp : TypeScript_Op<"TypeDescriptor", [Pure]> { let summary = "type name from the static descriptor of a type"; let description = [{ diff --git a/tslang/lib/TypeScript/LowerToAffineLoops.cpp b/tslang/lib/TypeScript/LowerToAffineLoops.cpp index 4e8cb80ba..a696d2a5e 100644 --- a/tslang/lib/TypeScript/LowerToAffineLoops.cpp +++ b/tslang/lib/TypeScript/LowerToAffineLoops.cpp @@ -2946,7 +2946,7 @@ void AddTsAffineLegalOps(ConversionTarget &target) mlir_ts::EndCatchOp, mlir_ts::BeginCleanupOp, mlir_ts::EndCleanupOp, mlir_ts::ThrowUnwindOp, mlir_ts::ThrowCallOp, mlir_ts::SymbolCallInternalOp, mlir_ts::CallInternalOp, mlir_ts::ReturnInternalOp, mlir_ts::NoOp, mlir_ts::SwitchStateInternalOp, mlir_ts::UnreachableOp, mlir_ts::GlobalConstructorOp, mlir_ts::AppendToUsedOp, - mlir_ts::CreateBoundFunctionOp, mlir_ts::TypeOfAnyOp, mlir_ts::BoxOp, mlir_ts::UnboxOp, + mlir_ts::CreateBoundFunctionOp, mlir_ts::TypeOfAnyOp, mlir_ts::IsTupleOfLayoutOp, mlir_ts::BoxOp, mlir_ts::UnboxOp, mlir_ts::CreateUnionInstanceOp, mlir_ts::GetValueFromUnionOp, mlir_ts::GetTypeInfoFromUnionOp, mlir_ts::OptionalOp, mlir_ts::OptionalValueOp, mlir_ts::OptionalUndefOp, mlir_ts::LoadLibraryPermanentlyOp, mlir_ts::SearchForAddressOfSymbolOp, diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index ae6f78a0a..6c54b8d82 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -480,7 +480,8 @@ class TypeDescriptorOpLowering : public TsLlvmPattern rewriter.replaceOp(op, ch.getOrCreateTypeDescriptorName(descriptorType, name, TypeOfOpHelper::typeKindFromName(name), - releaseRoutineName, retainRoutineName, variant)); + releaseRoutineName, retainRoutineName, variant, + TypeOfOpHelper::layoutIdOf(descriptorType))); return success(); } @@ -7829,6 +7830,28 @@ struct TypeOfOpLowering : public TsLlvmPattern } }; +struct IsTupleOfLayoutOpLowering : public TsLlvmPattern +{ + using TsLlvmPattern::TsLlvmPattern; + + LogicalResult matchAndRewrite(mlir_ts::IsTupleOfLayoutOp op, Adaptor transformed, + ConversionPatternRewriter &rewriter) const final + { + auto loc = op.getLoc(); + + TypeHelper th(rewriter); + TypeConverterHelper tch(getTypeConverter()); + + AnyLogic al(op, rewriter, tch, loc, tsLlvmContext->compileOptions); + TypeDescriptorLogic tdl(rewriter, tch, loc); + auto layout = tdl.getLayoutFromTag(al.getTypeOfAny(transformed.getValue())); + auto expected = rewriter.create( + loc, th.getI32Type(), rewriter.getI32IntegerAttr((int32_t)TypeOfOpHelper::layoutIdOf(op.getLayoutType()))); + rewriter.replaceOpWithNewOp(op, LLVM::ICmpPredicate::eq, layout, expected); + return success(); + } +}; + struct TypeOfAnyOpLowering : public TsLlvmPattern { using TsLlvmPattern::TsLlvmPattern; @@ -9494,7 +9517,7 @@ void TypeScriptToLLVMLoweringPass::runOnOperation() LoadSaveValueLowering, ThrowUnwindOpLowering, ThrowCallOpLowering, VariableOpLowering, DebugVariableOpLowering, AllocaOpLowering, InvokeOpLowering, AccessorUnwindEdgeOpLowering, InvokeHybridOpLowering, VirtualSymbolRefOpLowering, ThisVirtualSymbolRefOpLowering, ThisSymbolRefOpLowering, InterfaceSymbolRefOpLowering, NewInterfaceOpLowering, VTableOffsetRefOpLowering, LoadBoundRefOpLowering, StoreBoundRefOpLowering, CreateBoundRefOpLowering, - CreateBoundFunctionOpLowering, GetThisOpLowering, GetMethodOpLowering, TypeOfOpLowering, TypeOfAnyOpLowering, DebuggerOpLowering, + CreateBoundFunctionOpLowering, GetThisOpLowering, GetMethodOpLowering, TypeOfOpLowering, TypeOfAnyOpLowering, IsTupleOfLayoutOpLowering, DebuggerOpLowering, UnreachableOpLowering, SymbolCallInternalOpLowering, CallInternalOpLowering, CallHybridInternalOpLowering, ReturnInternalOpLowering, NoOpLowering, GlobalConstructorOpLowering, AppendToUsedOpLowering, ExtractInterfaceThisOpLowering, ExtractInterfaceVTableOpLowering, BoxOpLowering, UnboxOpLowering, DialectCastOpLowering, CreateUnionInstanceOpLowering, diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 639d909fd..37ad302a8 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -2744,8 +2744,8 @@ namespace mlirgen // read out of it, and anything else - a class object, a number - throws. It was read as the tuple's // layout whatever it held (`(<{ f: F }>x).f = g` with a class object in `x` wrote over its vtable). // `___check_tuple` only asks the box (it keeps nothing of it); the read after it is the raw one it - // was. A tuple of another layout passes the check: the box names no tuple's fields (`{ n: 5 }` - // holds an s32, read as a number). + // was. A tuple of other fields throws too: its descriptor's layout id is not the type's + // (ts.IsTupleOfLayout) - `{ n: 5 }` holds an s32, which was read as a number. ValueOrLogicalResult MLIRGenImpl::castAnyToTuple(mlir::Location location, mlir::Type type, mlir::Value value, const GenContext &genContext) { @@ -2756,8 +2756,10 @@ namespace mlirgen removeGenericFunctionMap(funcName); stringstream ss; - ss << S("function __check_tuple(a: any) {\n"); + ss << S("function __check_tuple(a: any, sameLayout: boolean) {\n"); ss << S("if (typeof a != 'tuple') throw \"Can't cast from any: the value is not an object of type '") + << stows(to_print(type)) << S("'\";\n"); + ss << S("if (!sameLayout) throw \"Can't cast from any: the object's fields are not those of type '") << stows(to_print(type)) << S("'\";\n}\n"); auto src = ss.str(); @@ -2780,8 +2782,10 @@ namespace mlirgen GenContext funcCallGenContext(genContext); funcCallGenContext.typeAliasMap.insert({".TYPE_ALIAS_T", type}); + // asked before the call: every box's tag has a descriptor, a tuple's or not SmallVector operands; operands.push_back(value); + operands.push_back(builder.create(location, getBooleanType(), value, mlir::TypeAttr::get(type))); NodeFactory nf(NodeFactoryFlags::None); auto checked = mlirGenCallExpression( diff --git a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp index 054564823..93ff3ad1a 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp @@ -273,6 +273,15 @@ namespace own_inference return true; } + // a tuple made of it only to be given to calls that keep none of it (isBorrow): the calls have + // it (an object literal's method, bound to the literal, read into the object type a parameter + // is - `applyT(p)` of a literal whose arrows capture, spec 66). Any other tuple keeps it. + if (mlir::isa(user) && isBorrow(user, use.get())) + { + values.push_back(user->getResult(0)); + return true; + } + // one of the values a select chooses between, not its condition if (auto selectOp = mlir::dyn_cast(user); selectOp && use.get() != selectOp.getCondition()) { diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index ba3f557da..da3627284 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -428,7 +428,7 @@ namespace own_inference // a test - `if (d)`, `d?.x`, `typeof u` - asks about the value, and keeps nothing if (mlir::isa(user)) + mlir_ts::TypeOfAnyOp, mlir_ts::IsTupleOfLayoutOp>(user)) { return true; } @@ -481,6 +481,18 @@ namespace own_inference } } + // ...and so does an object seen as the storage it points at, when only its fields are reached + // through it: each read of one is a place read (checkPlaceRead), as `o.w` straight off the + // object is. A cast to an object type reads an object literal's fields so (spec 66). + if (auto castOp = mlir::dyn_cast(user); + castOp && mlir::isa(castOp.getIn().getType()) && mlir::isa(castOp.getType())) + { + auto storage = castOp.getResult(); + return !storage.use_empty() && llvm::all_of(storage.getUsers(), [](mlir::Operation *storageUser) { + return mlir::isa(storageUser); + }); + } + // ...and so does a cast to `null` or `undefined`, which holds no block: `--di` records the // `r` that `if (r == null)` narrows as one if (auto castOp = mlir::dyn_cast(user)) @@ -501,6 +513,17 @@ namespace own_inference return !isKeptArgument(user, value); } + // ...and so is a tuple made of it only to be given to calls that keep none of it, and that + // nothing releases: an object literal's method bound to it, read into the object type a + // parameter is (`applyT(p)`, spec 66) + if (auto createTupleOp = mlir::dyn_cast(user)) + { + auto tuple = createTupleOp.getResult(); + return !tuple.use_empty() && llvm::all_of(tuple.getUses(), [&](mlir::OpOperand &use) { + return isCall(use.getOwner()) && !isCalleeOperand(use) && !isKeptArgument(use.getOwner(), tuple); + }); + } + // the array being pushed onto is written, not taken; what is inserted is taken if (auto pushOp = mlir::dyn_cast(user)) { diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index fae1da5a5..c564ec91a 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -389,6 +389,17 @@ namespace own_inference continue; } + // an object seen as the storage it points at, its fields read through it: the object + // (an object literal this function made is its own, `applyT(p)` of one whose arrows + // capture reads a method bound to it into the parameter's object type) + if (auto castOp = base.getDefiningOp(); + castOp && mlir::isa(castOp.getIn().getType()) && + mlir::isa(castOp.getType())) + { + bases.push_back(rootOf(castOp.getIn())); + continue; + } + // a result that borrows an argument is somewhere under the argument if (auto *call = borrowingCall(base)) { diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 2b21cc6c2..b7d7b6d05 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4007,7 +4007,7 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_generator_this_param own_copy_within_returned_param own_swap_elements own_callback_forwarded own_optional_record_read own_param_default_kept own_literal_into_array own_generator_take own_rest_array_borrows own_string_copies - own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take + own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_callback_shapes own_callback_extended own_callback_interface own_generic_specializations own_callback_cast own_callback_interface_slot) tslang_add_test(NAME test-jit-own-${own_test} COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") @@ -4045,7 +4045,7 @@ foreach(keeps_mm rc gc none) own_copy_within_returned_param own_swap_elements own_callback_forwarded own_optional_record_read own_param_default_kept own_literal_into_array own_generator_take own_rest_array_borrows own_string_copies - own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take + own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_callback_shapes own_callback_extended own_callback_interface own_generic_specializations own_callback_cast own_callback_interface_slot) tslang_add_test(NAME test-jit-${keeps_mm}-${keeps_test} COMMAND test-runner -jit -mm=${keeps_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${keeps_test}.ts") diff --git a/tslang/test/tester/own/own_literal_captures.ts b/tslang/test/tester/own/own_literal_captures.ts new file mode 100644 index 000000000..eba690211 --- /dev/null +++ b/tslang/test/tester/own/own_literal_captures.ts @@ -0,0 +1,61 @@ +// An object literal a variable is declared with, with no type, whose arrow functions capture locals +// around it (spec 66): given later to a parameter of an object type (`apply(o)`), each member is read +// out as a method bound to the literal, which the call only borrows; the literal is used after, given +// again, and given to an interface. Each step churns, so anything freed too early reads garbage; every +// model runs it. +class Item { + constructor(public n: number) {} +} + +interface Scaler { + w(x: number): number; +} + +function churn() { + const junk: Item[] = []; + for (let i = 0; i < 64; i++) junk.push(new Item(999)); +} + +function apply(o: { w: (x: number) => number }) { + return o.w(3); +} + +function applyBoth(o: { w: (x: number) => number; v: (x: number) => number }) { + return o.w(1) + o.v(2); +} + +function useScaler(s: Scaler) { + return s.w(2); +} + +function test(i: number) { + let s: number = 0; + const k: number = 2; + const o = { w: (x: number) => x * k }; + s += apply(o); + churn(); + s += o.w(1); + s += apply(o); + s += useScaler(o); + + const tag = "n" + i; + const t = { w: (x: number) => x + tag.length, v: (x: number) => x * k + tag.length }; + s += applyBoth(t); + churn(); + s += apply(t); + s += tag.length; + return s; +} + +function main() { + let ok = 0; + for (let i = 0; i < 300; i++) { + const len = ("n" + i).length; + // 6 + 2 + 6 + 4, then (1 + len) + (4 + len), (3 + len), len + if (test(i) == 18 + 8 + 4 * len) ok++; + churn(); + } + + assert(ok == 300, "ok"); + print("done."); +} diff --git a/tslang/test/tester/tests/00any_to_tuple.ts b/tslang/test/tester/tests/00any_to_tuple.ts index ee49c136b..239841616 100644 --- a/tslang/test/tester/tests/00any_to_tuple.ts +++ b/tslang/test/tester/tests/00any_to_tuple.ts @@ -33,5 +33,35 @@ function main() { assert(thrown); + // a tuple of other fields throws too: `{ n: 5 }` holds an s32, which was read as a number, and + // `{ m: 1.5 }` was read as if its field were `n` + thrown = false; + try { + const s: any = { n: 5 }; + asTuple(s); + } catch (e) { + thrown = true; + } + + assert(thrown); + + thrown = false; + try { + const m: any = { m: 1.5 }; + asTuple(m); + } catch (e) { + thrown = true; + } + + assert(thrown); + + // the same fields, from a literal of numbers and nested in another object + const f: any = { n: 2.5 }; + assert(asTuple(f).n == 2.5); + + const o: any = { p: { n: n }, s: "x" }; + const q = <{ p: { n: number }; s: string }>o; + assert(q.p.n == 5 && q.s == "x"); + print("done."); }