Skip to content

Fix thrown numbers never being caught, and const array mutation being discarded - #344

Merged
ASDAlexander77 merged 4 commits into
mainfrom
fix-throw-number
Sep 22, 2026
Merged

ASDAlexander77 merged 4 commits into
mainfrom
fix-throw-number

Conversation

@ASDAlexander77

Copy link
Copy Markdown
Owner

Summary

Two silent-failure bugs, both found while checking up on earlier reports.

1. Throwing a number ended the program silently

function main() { try { throw 42; } catch (e) { print("caught"); } print("done."); }

printed nothing at all — not the catch body, not the line after the try — and exited 0. The same with catch (e: any). Throwing a string worked.

On Windows, catch (e) and catch (e: any) lower to a single SEH catchpad filtering on the generic void* type descriptor ??_R0PEAX@8. Strings and class instances already carried a matching fallback entry in their CatchableTypeArray; int, float and double did not. A thrown number matched no filter, so the exception propagated out of main and the process ended quietly.

I32Type, F32Type and F64Type now get that fallback entry, as strings and classes do. Each gets its own CatchableType record rather than sharing _CT??_R0PEAX@88: that global is linkonce_odr, and reusing it corrupted the declared copy size for other types in the same module, which crashed 00try_catch.ts during development. The shared ??_R0PEAX@8 type descriptor stays shared, since it is the type identity.

2. Mutating a const array did nothing, or crashed

const arr = [3, 1, 2];
arr.sort((a, b) => a - b);   // arr stayed [3, 1, 2]
arr[0] = 9;                  // crashed (0xC0000005)

A const array literal resolved to !ts.const_array<T, N>, an immutable compile-time snapshot, instead of the heap-backed !ts.array<T> a let array gets. Plain const bindings never got real storage, so every mutation ran against a throwaway ts.Cast copy while reads still saw the pristine original. Both module-level and local const arrays were affected; let was not.

const array bindings now get identity storage and widening, in both the local and global paths.

castConstArrayToArray is extended to match. It recovers a const array's original literal to keep an existing feature working — a const int array assigned to, or passed as, a number[]. It previously only recognised the local shape (Load -> VariableOp). Once globals were widened too, the module-level shape (Load -> AddressOf) stopped matching and const nums: number[] = c; failed to compile at module scope. It now handles both, and falls back cleanly to a diagnostic when the initializer is not a literal.

Read-only const arrays are unaffected in cost: the constant is still built once in the global initializer, and reads are a load, not a copy.

Tests

  • 00throw_number_untyped_catch.ts asserts control flow only — the catch body runs, execution continues after the try — because reading a caught value is separately unreliable here.
  • 00const_array_mutation.ts covers mutation persisting through a const array's shared identity, and the direct element write that used to crash, at module and local scope. It avoids Array.sort, since suite tests run with --no-default-lib.
  • 00const_array_to_array_elements.ts gains module-scope cases for the widening feature above: assignment, argument and return value. Only the local shapes were covered before, which is why the regression above passed the suite.
  • The default library repo gains const_array_mutation.ts, covering the originally reported sort/reverse case against the real library.

Test plan

  • ctest -j 16 -C Release: 2794/2794 (2786 before, plus 8 new registrations).
  • The new tests pass under gc, rc and none, as both JIT and executables.
  • Checked by review in generated IR: three distinctly named fallback CatchableType records with correct sizes, no symbol reused across different sizes, and the array count fields consistent.
  • const array checks: read-only global arrays still build the constant once; exported const arrays are unchanged across modules; --verify-ownership under -mm=rc is clean.
  • Linux CI. The exception change is Windows-only; the const-array change is platform-independent.

Found, not fixed

Recorded here rather than silently left:

  • catch (e: number) still does not catch a bare integer literal: the literal throws as s32 while the catch filters on double. This is the known "integer literals are s32" divergence.
  • Throwing a boolean or a bigint is rejected at compile time ("Not supported type in throw"), before and after this change.
  • A module-level const array that aliases another one (const c = other;) still cannot widen to number[]: the trace-back unwraps casts, not a second level of global indirection. The local equivalent works incidentally, because the alias shares storage.

🤖 Generated with Claude Code

ASDAlexander77 and others added 4 commits September 22, 2026 23:33
… filter

On Windows, an untyped `catch (e)` and `catch (e: any)` both compile to a
single SEH catchpad that filters on the generic void*-shaped RTTI descriptor
used for `any` (`??_R0PEAX@8`). String and class throws already carried a
matching fallback entry in their CatchableTypeArray so that filter could find
them; `int`/`float`/`double` did not, so a thrown number's array held only its
own primitive descriptor, the filter never matched, and the exception
propagated out of `main` uncaught - the program printed nothing and exited 0.

Give I32Type/F32Type/F64Type their own second `.PEAX` catchable-type entry,
mirroring String/ClassType. Their fallback entry needs its own distinctly
named CatchableType record (not the shared pointer-sized `_CT??_R0PEAX@88`):
that global is linkonce_odr and idempotently skipped once created, so reusing
the shared name with a primitive-sized value silently poisoned the record's
declared copy size for every other type referencing it in the same module -
caught by the existing 00try_catch.ts suite test, which throws four different
types from one module.

Adds 00throw_number_untyped_catch.ts, asserting control flow only (not the
caught value, per the project's existing catch-value-is-unreliable rule).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`const arr = [3, 1, 2]` resolves to `!ts.const_array<T,N>`, a compile-time-
constant snapshot, not the mutable heap-backed `!ts.array<T>` a `let` array
gets (TS array *contents* are still mutable when the binding is `const` -
only reassigning `arr` is blocked). `registerVariable` 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, per docs/const-let-storage-design.md). So every
mutating-method call site (`.sort()`, `.reverse()`) had to `ts.Cast` a fresh,
disposable `!ts.array<T>` copy out of the pristine const_array and mutate
that instead, while direct element access indexed the immutable original
directly: mutations were silently lost, and `arr[i] = v` wrote into
read-only constant data and segfaulted (0xC0000005). This affected both
module-level and function-local `const` array literals; `let` arrays and
non-array `const` bindings were unaffected.

Fix: extend the existing needsIdentityStorage mechanism
(processConstRef/adjustLocalVariableType in MLIRGenImpl.h) to also trigger
for `!ts.const_array<T,N>`, and give it the same const_array -> array
widening `let` gets via wideStorageType, instead of the previous early
return that only widened non-const bindings. Module-level const arrays go
through a separate codegen path (createGlobalVariable /
adjustGlobalVariableType, which never calls processConstRef), so the same
widening was added there directly - the GlobalOp's own {ptr,len} header
still stays const (reassigning `arr` is still rejected), only its element
type is corrected to the mutable array representation.

Widening a const array's exposed type eagerly meant a later read of it no
longer carried its original `!ts.const_array` typing, which broke a
narrower, pre-existing feature: assigning/passing a `const` int-array
literal (`s32[]`) into a differently-element-typed array (`number[]`) relies
on `castConstArrayToArray` doing an elementwise widen at the literal's
original type. Fixed by teaching that function to trace back through
whichever shape the identity-storage fix introduces to recover the original
literal constant, so the elementwise conversion still applies:
 - local: Load -> VariableOp -> its initializer (a Cast chain)
 - module-level: Load -> AddressOf(@global) -> that GlobalOp's own
   initializer region, whose GlobalResultOp terminator yields the same kind
   of Cast chain

The first round of this fix only handled the local shape (found by the
existing local-only test, 00const_array_to_array_elements.ts); a review
caught that the module-level shape was still broken (`const c = [1,2,3];
const nums: number[] = c;` at module scope, and passing/returning such a
const array through a `number[]`-typed parameter/return, all rejected with
"element type number is not base of type s32"). Fixed by also unwrapping
the AddressOf(global) shape above, and extended
00const_array_to_array_elements.ts with a module-level const array literal
covering all three shapes (assignment, parameter, return value).

Adds a regression test, test/tester/tests/00const_array_mutation.ts,
registered in test/tester/CMakeLists.txt like its 00const_array_* neighbours
(test-compile-00-const-array-mutation / test-jit-00-const-array-mutation).
It does not call 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 exercises the
same "does mutation persist through the shared array identity" root cause
via a small hand-written in-place sort (element reads/writes plus a
function call) instead. The default-lib scenario itself (Array.sort()/
.reverse() on a const array) is covered separately in the DefaultLib repo's
own test suite (tests/const_array_mutation.ts, commit 1fba07c there), which
does run with the default library.

Full suite: 2794/2794 passing (Release, ctest -C Release; 2792 baseline
plus the 2 new registrations).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…catch-all

On Linux, an untyped `catch (e)` and `catch (e: any)` both resolve their
catch variable to `AnyType` (ANY_AS_DEFAULT), and TryOpLowering's landing
pad used MLIRRTTIHelperVCLinux::setType() to turn that into the literal
Itanium RTTI descriptor for `void*` (`_ZTIPv`) as the landingpad's typed
clause: `catch ptr @_ZTIPv`.

Per the Itanium ABI, a pointer-typed catch clause is not a catch-all - the
personality routine special-cases it to mean "catch any pointer-typed
exception" (which is why it already caught thrown strings/classes). A
thrown `int`/`double` is not a pointer, so it could never satisfy that
clause; __cxa_throw's handler search walked past every frame including
main and libstdc++ called std::terminate/abort. This is the Linux half of
the same defect c3e4b8c fixed for Windows - the same fallback-RTTI trick
does not apply here, because Linux's actual "catch anything" mechanism is
a clause-less `catch ptr null`, not a typed pointer clause.

Split MLIRRTTIHelperVCLinux's two setType() overloads by their real
callers: the one setRTTIForType() uses to pre-declare RTTI globals at
catch-declaration time keeps mapping AnyType to the `_ZTIPv` global (a
later `catch (e) { throw e; }` rethrow of that value still needs it to
exist), while the one TryOpLowering uses to pick the landing pad's clause
now treats AnyType as a no-op, so hasType() reports false and the existing
catch-all path (already used for a bare `catch {}` with no variable) emits
a real `catch ptr null` instead.

Verified by cross-emitting Linux-flavoured IR (--emit=llvm
-mtriple=x86_64-unknown-linux-gnu) on this Windows machine: untyped/any
catches of a thrown int now get `catch ptr null`; a typed `catch (e:
string)` is unchanged (`catch ptr @_ZTIPc` + llvm.eh.typeid.for); the
`catch (e) { throw e; }` rethrow idiom still references `_ZTIPv` for the
re-thrown any value and is still caught by the outer catch-all. Cannot
compile, link, or run on Linux from this machine, so the actual Linux CI
run remains unverified here. Windows IR for the same cases is byte-for-byte
unaffected (MLIRRTTIHelperVCWin32.h was not touched), and the full Windows
suite still passes 2794/2794.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
CI showed the Linux catch-all attempt (ff01e3a) trades one bug for
another: it made an untyped catch match a thrown number, and broke
reading the caught value. `00try_catch.ts` main4 does
`catch (v: any) { t = <int>v; }` and asserts the value, and that failed
on Linux in all six of its registrations while Windows stayed green.
Matching and binding have to be solved together there, which needs a
Linux machine to iterate on - this branch has neither.

So ff01e3a is reverted and `00throw_number_untyped_catch.ts` is
registered on Windows only, including its rc/none corpus variants. The
Windows fix it covers is unaffected: 2794/2794 locally, with all six of
its registrations passing.

What stays broken on Linux is recorded in the issue this commit's PR
links: an untyped catch clause is the void* type descriptor (_ZTIPv),
which the Itanium ABI matches only against pointer exceptions, so a
thrown number is never caught and the program aborts in std::terminate.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@ASDAlexander77

Copy link
Copy Markdown
Owner Author

CI found that the Linux attempt (ff01e3a) traded one bug for another: it made an untyped catch match a thrown number, but broke reading the caught value — 00try_catch.ts main4 (catch (v: any) { t = <int>v; }) failed in all six of its Linux registrations while Windows stayed green.

That commit is reverted, and 00throw_number_untyped_catch.ts is now registered on Windows only, including its rc/none corpus variants. The Windows fix this PR is about is unaffected (2794/2794 locally, all six registrations passing).

The Linux gap is filed as #345, with the reproduction, the cause (an untyped catch's clause is _ZTIPv, which the Itanium ABI matches only against pointer exceptions), and why matching and value binding have to be fixed together.

@ASDAlexander77
ASDAlexander77 merged commit 9664192 into main Sep 22, 2026
2 checks passed
@ASDAlexander77
ASDAlexander77 deleted the fix-throw-number branch September 22, 2026 23:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant