diff --git a/tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32.h b/tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32.h index 2be78603d..ea9ed870e 100644 --- a/tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32.h +++ b/tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32.h @@ -61,6 +61,12 @@ class LLVMRTTIHelperVCWin32 void setF32AsCatchType() { types.push_back({F32Type::typeName, F32Type::typeInfoRef, F32Type::catchableTypeInfoRef, F32Type::catchableTypeSize}); + // Same catchableTypeSize as the primary entry, not pointerSize(): both entries describe + // the exact same in-memory value (a double), and a size mismatch here would tell the CRT + // to copy pointerSize() bytes out of a catchableTypeSize()-byte object when a generic + // `catch (e)`/`catch (e: any)` matches via this fallback entry - see the note on + // I32Type::typeName2 in LLVMRTTIHelperVCWin32Const.h. + types.push_back({F32Type::typeName2, F32Type::typeInfoRef2, F32Type::catchableTypeInfoRef2, F32Type::catchableTypeSize}); catchableTypeInfoArrayRef = F32Type::catchableTypeInfoArrayRef; throwInfoRef = F32Type::throwInfoRef; @@ -69,6 +75,8 @@ class LLVMRTTIHelperVCWin32 void setF64AsCatchType() { types.push_back({F64Type::typeName, F64Type::typeInfoRef, F64Type::catchableTypeInfoRef, F64Type::catchableTypeSize}); + // see setF32AsCatchType for why this reuses the primary size instead of pointerSize() + types.push_back({F64Type::typeName2, F64Type::typeInfoRef2, F64Type::catchableTypeInfoRef2, F64Type::catchableTypeSize}); catchableTypeInfoArrayRef = F64Type::catchableTypeInfoArrayRef; throwInfoRef = F64Type::throwInfoRef; @@ -77,6 +85,9 @@ class LLVMRTTIHelperVCWin32 void setI32AsCatchType() { types.push_back({I32Type::typeName, I32Type::typeInfoRef, I32Type::catchableTypeInfoRef, I32Type::catchableTypeSize}); + // `int` is 4 bytes on every target, unlike a pointer - see setF32AsCatchType for why this + // reuses the primary size instead of pointerSize() + types.push_back({I32Type::typeName2, I32Type::typeInfoRef2, I32Type::catchableTypeInfoRef2, I32Type::catchableTypeSize}); catchableTypeInfoArrayRef = I32Type::catchableTypeInfoArrayRef; throwInfoRef = I32Type::throwInfoRef; diff --git a/tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32Const.h b/tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32Const.h index 289c1ad64..12414afbb 100644 --- a/tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32Const.h +++ b/tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32Const.h @@ -21,13 +21,38 @@ namespace windows constexpr const auto *typeInfoExtRef = "??_7type_info@@6B@"; constexpr const auto *imageBaseRef = "__ImageBase"; +// F32Type/F64Type/I32Type each also carry a second, `.PEAX` (void*) catchable-type entry - +// see the comment on StringType::typeName2 below for why: it is what lets an untyped +// `catch (e)` or a `catch (e: any)` (which filters on `??_R0PEAX@8`, the same generic +// void*-shaped RTTI used for `any`) match a thrown primitive at all. Without it the +// CatchableTypeArray the CRT walks contains only the primitive's own descriptor, the +// filter never matches, and the exception propagates out of `main` uncaught - see +// throw-number-catchable-type-missing-any-fallback.md. +// +// That fallback entry's *type descriptor* (`typeInfoRef2`, `??_R0PEAX@8`) is safe to share +// with String/Class/I8PtrType below: a type descriptor carries no size, just a vtable pointer +// and the `.PEAX` name. Its *catchable-type* record is not safe to share, though - it carries +// `sizeOrOffset`, and that value is genuinely different per primitive (4 for an `int`, 8 for a +// `double`, `pointerSize()` - 4 or 8 depending on target - for a string/class/`any` pointer). +// `_CT??_R0PEAX@88` is a `linkonce_odr` global keyed only by name: whichever translation unit +// or, within one module, whichever type gets processed first "wins" and fixes that symbol's +// size for every later reference to the same name (see `catchableType()`'s +// `lookupSymbol(...) -> return failure()` idempotency guard). Giving `I32Type` and +// `F32Type`/`F64Type` their own distinctly-named fallback records below keeps a module that +// throws both an `int` and a `string` (say) from having one of them silently take on the +// other's copy size. + namespace F32Type { constexpr const auto *typeName = ".N"; +constexpr const auto *typeName2 = ".PEAX"; constexpr const auto *typeInfoRef = "??_R0N@8"; +constexpr const auto *typeInfoRef2 = "??_R0PEAX@8"; constexpr const auto *catchableTypeInfoRef = "_CT??_R0N@88"; -constexpr const auto *catchableTypeInfoArrayRef = "_CTA1N"; -constexpr const auto *throwInfoRef = "_TI1N"; +// own record, not the pointer-shaped `_CT??_R0PEAX@88` - see the block comment above +constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@N88"; +constexpr const auto *catchableTypeInfoArrayRef = "_CTA2N"; +constexpr const auto *throwInfoRef = "_TI2N"; // describes `.N` (double), like F64Type - see setF32AsCatchType constexpr int catchableTypeSize = 8; } // namespace F32Type @@ -35,20 +60,28 @@ constexpr int catchableTypeSize = 8; namespace F64Type { constexpr const auto *typeName = ".N"; +constexpr const auto *typeName2 = ".PEAX"; constexpr const auto *typeInfoRef = "??_R0N@8"; +constexpr const auto *typeInfoRef2 = "??_R0PEAX@8"; constexpr const auto *catchableTypeInfoRef = "_CT??_R0N@88"; -constexpr const auto *catchableTypeInfoArrayRef = "_CTA1N"; -constexpr const auto *throwInfoRef = "_TI1N"; +// own record, not the pointer-shaped `_CT??_R0PEAX@88` - see the block comment above +constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@N88"; +constexpr const auto *catchableTypeInfoArrayRef = "_CTA2N"; +constexpr const auto *throwInfoRef = "_TI2N"; constexpr int catchableTypeSize = 8; } // namespace F64Type namespace I32Type { constexpr const auto *typeName = ".H"; +constexpr const auto *typeName2 = ".PEAX"; constexpr const auto *typeInfoRef = "??_R0H@8"; +constexpr const auto *typeInfoRef2 = "??_R0PEAX@8"; constexpr const auto *catchableTypeInfoRef = "_CT??_R0H@84"; -constexpr const auto *catchableTypeInfoArrayRef = "_CTA1H"; -constexpr const auto *throwInfoRef = "_TI1H"; +// own record, not the pointer-shaped `_CT??_R0PEAX@88` - see the block comment above +constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@84"; +constexpr const auto *catchableTypeInfoArrayRef = "_CTA2H"; +constexpr const auto *throwInfoRef = "_TI2H"; // 4, not the pointer size: `int` is 4 bytes on every target, and the `4` at the end of // `_CT??_R0H@84` says so too constexpr int catchableTypeSize = 4; diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCWin32.h b/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCWin32.h index bcf964d68..ab1466da0 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCWin32.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCWin32.h @@ -62,6 +62,10 @@ class MLIRRTTIHelperVCWin32 { types.push_back({windows::F32Type::typeName, windows::F32Type::typeInfoRef, windows::F32Type::catchableTypeInfoRef, windows::F32Type::catchableTypeSize}); + // Same catchableTypeSize as the primary entry, not pointerSize() - see the equivalent + // comment in LLVMRTTIHelperVCWin32.h::setF32AsCatchType. + types.push_back({windows::F32Type::typeName2, windows::F32Type::typeInfoRef2, windows::F32Type::catchableTypeInfoRef2, + windows::F32Type::catchableTypeSize}); catchableTypeInfoArrayRef = windows::F32Type::catchableTypeInfoArrayRef; throwInfoRef = windows::F32Type::throwInfoRef; @@ -71,6 +75,8 @@ class MLIRRTTIHelperVCWin32 { types.push_back({windows::F64Type::typeName, windows::F64Type::typeInfoRef, windows::F64Type::catchableTypeInfoRef, windows::F64Type::catchableTypeSize}); + types.push_back({windows::F64Type::typeName2, windows::F64Type::typeInfoRef2, windows::F64Type::catchableTypeInfoRef2, + windows::F64Type::catchableTypeSize}); catchableTypeInfoArrayRef = windows::F64Type::catchableTypeInfoArrayRef; throwInfoRef = windows::F64Type::throwInfoRef; @@ -80,6 +86,8 @@ class MLIRRTTIHelperVCWin32 { types.push_back({windows::I32Type::typeName, windows::I32Type::typeInfoRef, windows::I32Type::catchableTypeInfoRef, windows::I32Type::catchableTypeSize}); + types.push_back({windows::I32Type::typeName2, windows::I32Type::typeInfoRef2, windows::I32Type::catchableTypeInfoRef2, + windows::I32Type::catchableTypeSize}); catchableTypeInfoArrayRef = windows::I32Type::catchableTypeInfoArrayRef; throwInfoRef = windows::I32Type::throwInfoRef; diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index a92e2d425..bcecba2ec 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -921,14 +921,71 @@ namespace mlirgen // with only a warning. Such an array is built here from its elements, each cast to the element type. std::optional MLIRGenImpl::castConstArrayToArray(mlir::Location location, mlir::Type type, mlir::Value value, mlir::Type valueType, const GenContext &genContext) { - auto constArrayType = dyn_cast(valueType); auto arrayType = dyn_cast(type); - if (!constArrayType || !arrayType || constArrayType.getElementType() == arrayType.getElementType()) + if (!arrayType) + { + return std::nullopt; + } + + auto constArrayType = dyn_cast(valueType); + + // A `const` array literal (`const c = [1, 2]`) now gets real identity + // storage so mutating methods like .sort() share one heap array instead of + // a fresh disposable copy per call (see processConstRef / + // adjustLocalVariableType / adjustGlobalVariableType in MLIRGenImpl.h) -- + // which means reading `c` elsewhere yields the already-widened + // `!ts.array`, not the original `!ts.const_array` this function + // keys off. Trace back through whichever shape that widening introduced to + // recover the original literal, so the elementwise conversion below still + // applies to a `const` int-array literal read into e.g. `number[]`: + // - local: Load -> VariableOp -> its initializer (a Cast chain) + // - module-level: Load -> AddressOf(@global) -> that GlobalOp's + // initializer region, whose GlobalResultOp terminator yields the same + // kind of Cast chain (see createGlobalVariableInitialization) + mlir::Value literalValue = value; + if (!constArrayType) + { + if (auto loadOp = value.getDefiningOp()) + { + if (auto varOp = loadOp.getReference().getDefiningOp()) + { + if (auto init = varOp.getInitializer()) + { + literalValue = init; + } + } + else if (auto addressOfOp = loadOp.getReference().getDefiningOp()) + { + if (auto globalOp = theModule.lookupSymbol(addressOfOp.getGlobalNameAttr())) + { + if (auto *initBlock = globalOp.getInitializerBlock()) + { + if (auto globalResultOp = dyn_cast(initBlock->getTerminator())) + { + if (globalResultOp.getResults().size() == 1) + { + literalValue = globalResultOp.getResults().front(); + } + } + } + } + } + } + + while (auto castOp = literalValue.getDefiningOp()) + { + literalValue = castOp.getIn(); + } + + constArrayType = dyn_cast(literalValue.getType()); + } + + if (!constArrayType || constArrayType.getElementType() == arrayType.getElementType()) { return std::nullopt; } - auto constOp = value.getDefiningOp(); + auto constOp = literalValue.getDefiningOp(); auto elementAttrs = constOp ? dyn_cast(constOp.getValue()) : mlir::ArrayAttr(); if (!elementAttrs) { diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index ef34c6ec6..dcf944a23 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -1424,8 +1424,22 @@ class MLIRGenImpl // pointer-like representation -- it still needs real storage so that // mutation through the bound method is visible across property accesses. // See docs/const-let-storage-design.md. + // + // A `const` array LITERAL is the same shape of problem: its resolved type + // is `!ts.const_array`, a compile-time-constant snapshot, not the + // mutable heap-backed `!ts.array` that TS array semantics require (a + // `const` binding only blocks *reassigning* `arr`, not mutating its + // contents). `let`/`var` widen const_array -> array once at declaration + // (adjustLocalVariableType -> wideStorageType) and keep that single heap + // array alive via real storage; `const` skipped both steps, so every call + // site needing `!ts.array` (e.g. `.sort()`/`.reverse()`) had to + // `ts.Cast` the pristine const_array into a fresh, disposable copy, while + // direct element access indexed the immutable original directly - + // mutating methods silently did nothing (they mutated a copy nobody kept) + // and `arr[i] = v` segfaulted (write into read-only constant data). + // Force the same real-storage + widening path as `let` for this case too. MLIRTypeHelper mth(builder.getContext(), compileOptions); - needsIdentityStorage = mth.hasBoundMethodField(type); + needsIdentityStorage = mth.hasBoundMethodField(type) || isa(type); if (needsIdentityStorage) { return mlir::success(); @@ -1629,6 +1643,29 @@ class MLIRGenImpl if (variableDeclarationInfo.isConst) { + // A const array literal (`!ts.const_array`) that was routed into real + // storage by processConstRef's needsIdentityStorage check still needs the + // same const_array -> array widening `let` gets below - storage alone is + // not enough. Without it, the Variable slot would hold the immutable + // const_array value itself, and each mutating use (.sort(), element + // write, ...) would still `ts.Cast` a fresh, disposable !ts.array copy + // out of it instead of sharing one heap array through the slot. Every + // other const type (generator wrapper tuples, plain values) keeps the + // early-return: this widening is only valid/needed for const_array. See + // docs/const-let-storage-design.md and the const-array note above + // processConstRef. + if (isa(type) && variableDeclarationInfo.needsIdentityStorage) + { + auto actualType = mth.removeConstType(type); + if (variableDeclarationInfo.initial && actualType != type) + { + CAST_A(castedValue, location, actualType, variableDeclarationInfo.initial, genContext); + variableDeclarationInfo.setInitial(castedValue); + } + + variableDeclarationInfo.setType(actualType); + } + return mlir::success(); } @@ -1655,6 +1692,31 @@ class MLIRGenImpl { if (variableDeclarationInfo.isConst) { + // Same const-array widening as adjustLocalVariableType, for a module-level + // `const arr = [...]`: a global const binding never goes through + // processConstRef (that path is local-only), so needsIdentityStorage is + // never computed for it - but the GlobalOp itself is always real storage, + // so no extra identity check is needed here, just the type widening. The + // GlobalOp stays `isConst` (its own {ptr,len} header can't be + // reassigned - `arr = other` is still rejected) but the header's type must + // be the heap-backed `!ts.array`, not the immutable `!ts.const_array + // ` snapshot, or every mutating method/element write still operates + // on a disposable ts.Cast copy or the read-only original. See the note + // above processConstRef / const-let-storage-design.md. + if (isa(variableDeclarationInfo.type)) + { + auto type = variableDeclarationInfo.type; + auto actualType = mth.removeConstType(type); + if (variableDeclarationInfo.initial && actualType != type) + { + auto result = cast(location, actualType, variableDeclarationInfo.initial, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(result) + variableDeclarationInfo.initial = V(result); + } + + variableDeclarationInfo.setType(actualType); + } + return mlir::success(); } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index b687c624c..a7cbfeeab 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -297,6 +297,7 @@ tslang_add_test(NAME test-compile-00-typeof-static-fold-conditions COMMAND test- tslang_add_test(NAME test-compile-00-typeof-union-narrowing COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00typeof_union_narrowing.ts") tslang_add_test(NAME test-compile-00-const-array-to-array-elements COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00const_array_to_array_elements.ts") tslang_add_test(NAME test-compile-00-const-array-nested-elements COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00const_array_nested_elements.ts") +tslang_add_test(NAME test-compile-00-const-array-mutation COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00const_array_mutation.ts") tslang_add_test(NAME test-compile-00-array-move-wide-elements COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00array_move_wide_elements.ts") tslang_add_test(NAME test-compile-00-bigint-struct-layout COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00bigint_struct_layout.ts") tslang_add_test(NAME test-compile-00-union-member-padding COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00union_member_padding.ts") @@ -386,6 +387,12 @@ tslang_add_test(NAME test-compile-00-owned-locals COMMAND test-runner "${PROJECT tslang_add_test(NAME test-compile-00-try-using-catch COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_using_catch.ts") tslang_add_test(NAME test-compile-00-throw-in-catch COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00throw_in_catch.ts") tslang_add_test(NAME test-compile-00-throw-inlined COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00throw_inlined.ts") +# Windows only: the fix this pins down is in the Win32 RTTI tables. On Linux an untyped catch +# still does not match a thrown number (the clause is a void* pointer type, which the Itanium ABI +# matches only against pointer exceptions), so this test fails there. See the Linux catch issue. +if (WIN32) +tslang_add_test(NAME test-compile-00-throw-number-untyped-catch COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00throw_number_untyped_catch.ts") +endif() tslang_add_test(NAME test-compile-00-using-nested-scopes COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_nested_scopes.ts") tslang_add_test(NAME test-compile-00-using-unwind-progress COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_unwind_progress.ts") tslang_add_test(NAME test-compile-00-break-continue-scope-exit COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00break_continue_scope_exit.ts") @@ -723,6 +730,7 @@ tslang_add_test(NAME test-jit-00-typeof-static-fold-conditions COMMAND test-runn tslang_add_test(NAME test-jit-00-typeof-union-narrowing COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00typeof_union_narrowing.ts") tslang_add_test(NAME test-jit-00-const-array-to-array-elements COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00const_array_to_array_elements.ts") tslang_add_test(NAME test-jit-00-const-array-nested-elements COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00const_array_nested_elements.ts") +tslang_add_test(NAME test-jit-00-const-array-mutation COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00const_array_mutation.ts") tslang_add_test(NAME test-jit-00-array-move-wide-elements COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00array_move_wide_elements.ts") tslang_add_test(NAME test-jit-00-funcs-expression-generic COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00funcs_expression_generic.ts") tslang_add_test(NAME test-jit-00-funcs-expression-iterator COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00funcs_expression_iterator.ts") @@ -807,6 +815,10 @@ tslang_add_test(NAME test-jit-00-new-delete COMMAND test-runner -jit "${PROJECT_ tslang_add_test(NAME test-jit-00-owned-locals COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00owned_locals.ts") tslang_add_test(NAME test-jit-00-throw-in-catch COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00throw_in_catch.ts") tslang_add_test(NAME test-jit-00-throw-inlined COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00throw_inlined.ts") +# Windows only, for the reason given at the compile registration above. +if (WIN32) +tslang_add_test(NAME test-jit-00-throw-number-untyped-catch COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00throw_number_untyped_catch.ts") +endif() tslang_add_test(NAME test-jit-00-using-nested-scopes COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_nested_scopes.ts") tslang_add_test(NAME test-jit-00-using-unwind-progress COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_unwind_progress.ts") tslang_add_test(NAME test-jit-00-break-continue-scope-exit COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00break_continue_scope_exit.ts") @@ -1697,6 +1709,7 @@ set(TSLANG_CORPUS 00symbol.ts 00throw_in_catch.ts 00throw_inlined.ts + 00throw_number_untyped_catch.ts 00to_primitive_ops.ts 00toplevel_control_flow.ts 00toplevel_no_main_with_helpers.ts @@ -1998,6 +2011,14 @@ set(TSLANG_CORPUS_BROKEN_AOT_RC set(TSLANG_CORPUS_BROKEN_AOT_NONE ) +# Windows-only corpus entries. 00throw_number_untyped_catch.ts pins down a Win32 RTTI fix; the +# same bug is still open on Linux (an untyped catch's clause is a void* pointer type there, which +# the Itanium ABI matches only against pointer exceptions), so the file would fail its rc/none +# corpus variants on Linux. Its explicit registrations are guarded the same way. +if (NOT WIN32) + list(REMOVE_ITEM TSLANG_CORPUS 00throw_number_untyped_catch.ts) +endif() + foreach(corpus_file ${TSLANG_CORPUS}) string(REGEX REPLACE "\\.ts$" "" corpus_slug "${corpus_file}") string(REGEX REPLACE "[_.]" "-" corpus_slug "${corpus_slug}") diff --git a/tslang/test/tester/tests/00const_array_mutation.ts b/tslang/test/tester/tests/00const_array_mutation.ts new file mode 100644 index 000000000..237d99fc5 --- /dev/null +++ b/tslang/test/tester/tests/00const_array_mutation.ts @@ -0,0 +1,60 @@ +// regression test: mutating a `const` array through an alias (element writes, and a +// helper function that reorders elements in place) silently did nothing - or crashed - +// both at module scope and inside a function body. +// +// Root cause: a `const` array literal resolves to `!ts.const_array` (a +// compile-time-constant snapshot), not the mutable heap-backed `!ts.array` a +// `let` array gets. `registerVariable`/`adjustLocalVariableType` never gave a plain +// `const` binding real storage or widened its type the way `let` does (only a +// narrower case -- a bound-method-carrying tuple, e.g. a generator wrapper -- forced +// real storage). So every mutating use had to `ts.Cast` a fresh, disposable +// `!ts.array` copy out of the pristine const_array, while direct element +// reads/writes indexed the immutable original directly: mutation through a passed-in +// array parameter (or a chain of them) was lost, and a direct element write into the +// immutable original segfaulted (0xC0000005). `let` arrays, and non-array mutating +// const bindings, were unaffected. +// +// This deliberately avoids Array.prototype.sort()/.reverse() (the methods in the +// original bug report): those are default-lib extension methods, and this suite's +// `test-runner` always passes `--no-default-lib`, so it writes its own tiny in-place +// sort out of plain element reads/writes/function calls instead - the same shape of +// mutation-through-identity that Array.sort()/.reverse() exercise, without the +// default-lib dependency. See docs/const-let-storage-design.md and the const-array +// notes next to processConstRef/adjustLocalVariableType/adjustGlobalVariableType in +// MLIRGenImpl.h. +const moduleArr: number[] = [3, 1, 2]; + +function swap(a: number[], i: number, j: number) { + const t = a[i]; + a[i] = a[j]; + a[j] = t; +} + +// tiny in-place bubble sort over 3 elements, written out longhand instead of a loop +// so this test has no dependency beyond plain control flow and array indexing. +function sort3(a: number[]) { + if (a[0] > a[1]) { swap(a, 0, 1); } + if (a[1] > a[2]) { swap(a, 1, 2); } + if (a[0] > a[1]) { swap(a, 0, 1); } +} + +function localMutation() { + const arr: number[] = [3, 1, 2]; + sort3(arr); + assert(arr[0] == 1 && arr[1] == 2 && arr[2] == 3, "local const: sort via aliased element writes"); + + arr[0] = 9; + assert(arr[0] == 9 && arr[1] == 2 && arr[2] == 3, "local const: direct element write"); +} + +function main() { + localMutation(); + + sort3(moduleArr); + assert(moduleArr[0] == 1 && moduleArr[1] == 2 && moduleArr[2] == 3, "module const: sort via aliased element writes"); + + moduleArr[0] = 9; + assert(moduleArr[0] == 9 && moduleArr[1] == 2 && moduleArr[2] == 3, "module const: direct element write"); + + print("done."); +} diff --git a/tslang/test/tester/tests/00const_array_to_array_elements.ts b/tslang/test/tester/tests/00const_array_to_array_elements.ts index 312033441..a28ba8f58 100644 --- a/tslang/test/tester/tests/00const_array_to_array_elements.ts +++ b/tslang/test/tester/tests/00const_array_to_array_elements.ts @@ -6,6 +6,25 @@ function lengthOf(u: number[] | string) { return typeof u === "array" ? u.length : -1; } +// A module-level `const` int-array literal: covers the same elementwise widening as the local +// `const c` case below, but through the global-variable codegen path (createGlobalVariable / +// adjustGlobalVariableType), not the local one (createLocalVariable / adjustLocalVariableType). +// Giving `const` array literals real identity storage (so mutating methods like .sort() share one +// heap array - see docs/const-let-storage-design.md) initially broke this: reading `moduleConst` +// back yields `AddressOf(@moduleConst) -> Load`, a shape castConstArrayToArray's local-only +// trace-back (Load -> VariableOp -> initializer) did not recognize, so it fell through to the +// generic array-to-array cast and was rejected ("element type number is not base of type s32"). +// Fixed by also unwrapping AddressOf(global) -> the GlobalOp's own initializer terminator. +const moduleConst = [7, 8, 9]; + +function takesNumberArray(a: number[]) { + return a[0] + a[1] + a[2]; +} + +function returnsNumberArray(): number[] { + return moduleConst; +} + function main() { const c = [1, 2, 3]; let fromConst: number[] = c; @@ -34,5 +53,15 @@ function main() { const halves: number[] = c; assert(halves[0] / 2 == 0.5, "number arithmetic on converted element"); + // module-level const int-array literal: assignment, parameter, and return-value shapes + let fromModuleConst: number[] = moduleConst; + assert(fromModuleConst.length == 3, "module const: length"); + assert(fromModuleConst[0] / 2 == 3.5, "module const: assignment, number arithmetic"); + + assert(takesNumberArray(moduleConst) == 24, "module const: parameter"); + + let returned = returnsNumberArray(); + assert(returned[2] / 2 == 4.5, "module const: return value, number arithmetic"); + print("done."); } diff --git a/tslang/test/tester/tests/00throw_number_untyped_catch.ts b/tslang/test/tester/tests/00throw_number_untyped_catch.ts new file mode 100644 index 000000000..08b43e435 --- /dev/null +++ b/tslang/test/tester/tests/00throw_number_untyped_catch.ts @@ -0,0 +1,89 @@ +// A thrown primitive number has to be catchable by a generic handler, not just by a handler +// declared with the exact matching numeric type. +// +// Root cause: on Windows, an untyped `catch (e)` and a `catch (e: any)` both compile to a +// single SEH catchpad that filters on the same generic `void*`-shaped RTTI descriptor used for +// `any` (`??_R0PEAX@8`). For that filter to match, the thrown value's ThrowInfo has to list a +// compatible `.PEAX` CatchableType entry alongside its own - which is exactly what a thrown +// string or class instance already carries (see StringType::typeName2 / ClassType::typeName2 +// in LLVMRTTIHelperVCWin32Const.h). `int`, `float`, and `double` did not carry that second +// entry, so a thrown number's CatchableTypeArray held only its own primitive descriptor; the +// generic filter never found a match, __CxxFrameHandler3 walked past `main` with nothing left +// to catch it, and the process quietly ended instead of running the catch body. +// +// Do NOT assert on the caught value here - see 00catch_value.ts's note (item 5am) on why +// reading a `catch` binding is a separate, already-tracked, back-end-dependent question. This +// file only asserts control flow: the catch body runs, and the statement after the try/catch +// still runs too. + +function untypedCatchesInt() { + let ran = 0; + try { + throw 42; + } + catch (e) { + ran = 1; + } + ran = ran + 10; + return ran; +} + +function anyCatchesInt() { + let ran = 0; + try { + throw 42; + } + catch (e: any) { + ran = 1; + } + ran = ran + 10; + return ran; +} + +function untypedCatchesFloat() { + let ran = 0; + try { + throw 2.5; + } + catch (e) { + ran = 1; + } + ran = ran + 10; + return ran; +} + +function anyCatchesFloat() { + let ran = 0; + try { + throw 2.5; + } + catch (e: any) { + ran = 1; + } + ran = ran + 10; + return ran; +} + +// a `number`-typed value (not a bare literal) thrown and caught the same way +function untypedCatchesNumberVar() { + let n: number = 42; + let ran = 0; + try { + throw n; + } + catch (e) { + ran = 1; + } + ran = ran + 10; + return ran; +} + +function main() { + assert(untypedCatchesInt() == 11, "an untyped catch must catch a thrown int and control flow must continue"); + assert(anyCatchesInt() == 11, "a `catch (e: any)` must catch a thrown int and control flow must continue"); + assert(untypedCatchesFloat() == 11, "an untyped catch must catch a thrown float and control flow must continue"); + assert(anyCatchesFloat() == 11, "a `catch (e: any)` must catch a thrown float and control flow must continue"); + assert(untypedCatchesNumberVar() == 11, "an untyped catch must catch a thrown `number` variable and control flow must continue"); + + print("done."); +}