A typed-array read that may name a missing element lowers to a boxed
`number | undefined`, and the optional-value analysis widens every
parameter it reaches for all callers. Two patterns in tsc-ts's relater
boxed its hottest relation methods this way, failing the build's scalar
ABI check ("Boxed numeric arguments in Checker.isTypeAssignableTo"):
- `const regular = this.regularTypes[id]; const sourceId = regular >= 0
? regular : id;` The read is NaN-coded, but its occurrence in the true
arm was rebuilt as `number | undefined`, so `sourceId` and the
parameters of isSimpleTypeRelatedTo and structuredTypeRelatedTo were
boxed. A comparison with a number that is never NaN is false for
undefined and NaN alike, so an occurrence of a never-reassigned binding
under such a guard is a plain, non-NaN number. The analysis now treats
it as one wherever it flows.
- `for (let i = 0; i < sources.length; i++) isTypeAssignableTo(sources[i],
targets[i])` over two Uint32Arrays allocated with the same length. The
parameters also receive a JSON field that may be NaN, so NaN-coding
cannot carry them (`source === target` must tell NaN from undefined).
The reads are now proven present instead: the index is a non-negative
integer counter that only its own function writes, a dominating guard
bounds it by the array's length or by the length of a parallel typed
array allocated with the same length, and each array is a `const`
fixed-length typed array referenced only through element accesses and
`.length`, so no code can detach its buffer. A proven-present read
lowers to the plain element read and is never optional.
indexReadInBounds also accepts a read inside an `if` condition and takes
an optional same-length fact. Reads the proofs do not cover keep the
established lowering: an inclusive bound, a shorter parallel array, a
decreasing or fractional counter, a counter a closure writes, and an
array that escapes all still read undefined, as the new corpus program
typed-array-present-reads checks against Node.
A typed-array element read answers undefined for an index outside
[0, length), so the default lowering returns a heap-boxed
`number | undefined` and widens every binding, parameter and return the
read reaches. In the tsc-ts scanner that boxed every character read and
turned every character predicate (isLineBreak, isIdentifierPart, ...)
into a function taking a boxed union.
Most consumers cannot tell undefined from NaN: relational, arithmetic
and bitwise operators, truthiness, Math functions, String.fromCharCode,
typed-array indexing, switch over number cases, and equality with a
number that is never undefined. The new analysis (nan-coded-reads.ts)
follows reads through local bindings, parameters of directly called
functions and methods (no overrides, no value uses), and their returns.
A slot is NaN-coded when every value it receives is a NaN-coded read or
slot, or any other number (converted with ToNumber on entry), and either:
- it never holds a genuine NaN (integer elements, integer constants,
guarded integer arithmetic), so NaN stands for undefined exactly; any
consumer that takes the value whole (an argument, a stored or returned
value, a literal element, concatenation) gets the exact
`number | undefined` rebuilt, and the optional-read analysis treats
that occurrence as optional, so it lowers as before; or
- every consumer is NaN-insensitive.
Equality of two NaN-coded values that never hold a genuine NaN also
answers true for two NaNs, as undefined === undefined does. Any other
slot keeps the established union lowering; asserted reads (`t[i]!`) are
unchanged.
tsc-ts best-v1 (scriptc main + this commit vs main, Linux sandbox,
Xeon 2.5 GHz, interleaved, medians of 5, diagnostics identical):
| app | parse | total (single-threaded) | wall --checkers 8 |
| --- | --- | --- | --- |
| tRPC | 1.263 -> 0.866 s (-31.4%) | 3.035 -> 2.527 s (-16.7%) | -13.0% |
| Excalidraw | 2.637 -> 1.865 s (-29.3%) | 14.99 -> 14.04 s (-6.3%) | -16.2% |
| Playwright | 3.150 -> 2.202 s (-30.1%) | 12.93 -> 12.14 s (-6.1%) | -12.4% |
| TypeORM | 2.562 -> 2.036 s (-20.5%) | 10.93 -> 10.46 s (-4.3%) | -8.6% |
| self-check | 2.080 -> 1.529 s (-26.5%) | 7.06 -> 6.68 s (-5.4%) | -15.1% |
The tsc-ts IR has 646 instead of 697 scr_union_new_f64 sites (the rest
are cold), 22 instead of 168 typed-read helper calls, and 217 instead of
572 scr_union_get_f64 calls; the scanner's hot functions allocate no
union boxes. Binary size -0.2%.
A closure created above the `let`/`const` it captures holds the binding
in a TDZ box whose NULL payload slot marks "not yet initialized". A
union of one reference arm with `null` and/or `undefined` (`Set<T> |
null`, `string | undefined`, `C | null`) is represented as the bare arm
pointer with NULL standing for the unit arm, so storing that unit value
made the box indistinguishable from the temporal dead zone: every later
read or write threw "Cannot access 'x' before initialization" although
the declaration had run.
The self-hosted compiler trips on exactly this shape in
lowerer.ts (`let dynamicViews: Set<string> | null = null`, read by a
callback created earlier), which made scriptc 0.2.8 fail to build
tsc-ts's relater with SC3004. Node evaluates the source correctly; the
native code was wrong.
TDZ boxes of nullable-union bindings now start at the module's immortal
NULLABLE_ABSENT sentinel and the TDZ test compares against it. No value
of the binding can hold that sentinel, and every RC entry point and the
cycle collector already skip it, so box release, trace and the
initializing store need no other change.
Corpus: 4596-tdz-nullable-forward-capture.
The class method census marks a method name as replaceable when a
function-typed property write uses that name, so a scanner storing its
error callback in `this.onError` made every call of any class's
`onError` method go through the checked property bag. That bag is a
dynamic store naming any property, so the int32 slot analysis also gave up
int32 storage for every class field exposed to dynamic code.
A function-typed write now marks the name only when an instance of a class
that has the method can inhabit the receiver's type: an assignability check
against the instance types of the method's owners, with `this` in an
instance member read as its class. Generic or anonymous owners, `this`
outside instance members, type parameters, `any` and `unknown` receivers
keep the conservative answer. Writes through interfaces or subclasses that
can reach a method still replace it.
Test: class-method-mutations.test.ts. Corpus:
4597-callback-field-method-name.
A class extending Error without its own constructor (or one passing
options to super) initializes the builtin prefix through the
error.ctorOptions helper, whose message and options arguments are dynamic.
The int32 slot analysis did not list that helper among the dynamic helpers
that never store into a live class view, so a single such class anywhere in
a program counted as a dynamic store naming every property: every f64
field of every class exposed to dynamic code lost its int32 storage, and
the integer facts of the functions reading those fields went with it.
error.ctorOptions runs scr_error_init_options, the same initializer
error.newOptions (already listed) runs: it stamps the receiver's
runtime-owned error prefix and only reads `options.cause`. In the native
tsc-ts self-check, two such classes cost 7% total time and 10% check time.
Unit test: int32-slots.test.ts. Corpus: 4596-error-subclass-int-fields
pins Error subclasses forwarding message and options beside integer
fields.
A field shared by every class arm of a union could only be read or
written when all arms declared it with one IR type. Syntax-tree code
commonly narrows a node to several classes with `instanceof` where one
class declares the field optional and another required (`initializer:
Expression | undefined` beside `initializer: Expression`), or as a
subclass beside its base, and both forms were refused.
Reads now dispatch on the union tag, read each arm's own slot, and widen
it to the arm field type every other one converts into without a check
(a union wrap or class upcast); the caller narrows the result to the
checker's flow type as before. Writes evaluate the value once as the arm
field type that every other arm's storage accepts and widen it per arm.
Arms whose field types are unrelated keep the existing refusal.
Corpus: 4594-union-class-field-mixed-types.
A parameter typed as a base class becomes runtime-optional storage
(`Base | undefined`) when a caller can pass an array hole. After
`instanceof` narrowed it to several subclasses and a guard such as
`node.label === undefined` ended its active runtime-optional state, the
next `node.label` lowered the receiver as the storage union, which has no
retag to the checker's class union, and the shared field read or write was
refused. Union property reads and union field writes now convert such a
receiver with the checked extraction and class test that typed slots
already use.
Corpus: 4595-union-class-field-optional-receiver.
A shorthand property and an object literal passed as an argument no
longer widen the declared record layout of the binding or parameter
that receives them. A widened layout made every existing record that
flowed into that binding or parameter convert to a copy, so later
writes through the copy were lost. Those literals keep a missing
element in their own fields and convert, with a check, into a declared
record.
The debug-variables fixture iterates an array whose elements may be
undefined, so its loop binding keeps the union layout the debugger
check inspects.
The new @scriptc/threads package exports publish(value) and
sharesPublishedGraphs. Node.js runs its JavaScript: publish validates
the whole graph (plain objects, arrays, class instances, Maps, Sets and
primitives other than symbols), then deep-freezes it, and published Maps
and Sets reject mutation. scriptc builds lower both exports to
intrinsics and never compile the package body.
In scriptc, publish makes the graph immutable and immortal: a
compiler-emitted walker per static type (llvm/publish.ts) marks every
object rc == SIZE_MAX through a runtime worklist (scr_publish.c), so
retains, releases and the collector skip it and nothing frees it, and
the objects leave the collector's buffers. Hierarchy members dispatch on
the concrete class; arrays, maps, sets, strings and dyn subgraphs have
runtime walkers. Static types over-approximate a graph, so an
unpublishable type gets a refusing walker that fails only when a value
is present, and every mark is logged so a refusal restores the whole
graph, exactly like the Node implementation's validate-first order.
A typed-ref capsule over a published object travels through postMessage
and workerData as a pointer (a fresh capsule in the receiver; vtables,
adapters and type keys are process-wide); immortal dyn graphs inside a
message are shared the same way. Iterating a published map no longer
writes its iteration depth.
Stores into the static types a program publishes (computed by
backend/publication.ts, a class with its whole hierarchy) carry a guard
that throws Node's frozen-object TypeErrors, and may-throw counts them.
The corpus program pins the contract against Node: shared and cyclic
class graphs with arrays, maps, sets and records read identically on
both threads, every write form fails with Node's message, unpublished
instances of the same classes stay writable, a refused publish leaves
its graph unchanged, and a worker-published graph reaches the main
thread. packages/threads/README.md documents the contract and the
differences (prototypes and identity across messages).
Each mark records its object kind, so a successful publish takes the
objects out of the RC audit's live counts (immortal objects are never
freed).
Dates (time values) and process streams (descriptors) are scalars in
scriptc, so their walkers refuse a date field or root directly instead
of pushing its bits as a pointer; the refusal corpus program pins the
statically typed refusals (date, function, RegExp, typed array and Error
values in class and record fields, and a date root) against Node.
Main lowers a discarded or union-typed `xs.pop()` to a length
truncation; those stores now carry a `pop` marker so a published array
fails with pop's own TypeError ("Cannot delete property 'N'", or the
length message for an empty array, whose `length = 0` store the emitter
drops unless the array type can be published).
A postMessage or workerData graph whose objects and arrays are all
frozen, ordinary and hold only primitives, strings and such containers
is now shared by pointer: every node and string becomes immortal
(rc == SIZE_MAX, so retains, releases and the cycle collector skip it
and nothing frees it), strings cache their key hash first, and the
nodes leave the sender's cycle buffers. Posting an already published
root is O(1). Anything else is cloned as before; SCRIPTC_PUBLISH=0
turns publication off and SCRIPTC_PUBLISH_TRACE=1 reports each choice.
With the receiver freezing what it receives (Node's clone is not
frozen) and no identity comparison across messages, the behavior
matches Node's structured clone. Published nodes leave the RC audit's live counts, since they are never
freed, and the small-integer dyn cache becomes process-wide (filled
before main): a published graph can outlive the thread that created its
nodes, and the thread-local table died with its thread.
The new corpus program pins that
contract both ways, including a worker-published graph read after the
worker exited and a shallowly frozen graph that must still be cloned.
Positional arguments of Math.hypot now take the same undefined-to-NaN
conversion as Math.max, Math.min and the fixed-arity statics, and a
direct indexed read that can miss converts the same way as a binding
holding one.
A for-of loop over an array whose own facts show a hole or a stored
undefined binds T | undefined, and the typed parameters, locals, record
fields and Math arguments it reaches widen to hold it. Loops over arrays
the element-state analysis proves free of holes read each element
directly, without a per-element state test.
Object literals built from a missing-element read keep the property as
undefined in shorthand and long form, through spreads, nested records,
arrays of records, annotated locals and literal arguments to typed
parameters.
A worker's messages and its uncaught 'error' event reach the parent on
separate channels in Node, so their relative order is not specified and
can differ under load. The fixture now records both and reports them when
the worker exits, which Node and native executables deliver after both.
Compiler caches keyed by programs and lowering passes move onto the
objects that own their lifetime, and the field-creation pass recognizes
its own writes by their receiver temporaries. A source test keeps weak
collections out of the compiler. Records and arrays that reach an
untyped slot through a union now keep their identity, and empty object
literals are keyed by their native object, so both work as WeakMap and
WeakSet keys instead of failing at runtime.
Worker programs sent every typed-array element read and write through
scr_bytes_get/scr_bytes_set, which take the shared-memory lock guard
even for buffers no other thread can see (4% of a Worker build of the
tsc-ts self-check). A view's `shared` storage is fixed before script
code can see it, so the emitted access now tests it: SharedArrayBuffer
views keep the locked runtime call, every other view takes the ordinary
inline path of non-worker programs.
The new corpus program reads and writes own and shared views through
the same functions (clamping, wrapping, float narrowing, out-of-range
and negative indices) on both threads.
Async functions and generators run on their own fiber stacks. The new
stack-overflow guard keeps a quarter of each stack as a reserve for
unwinding and error reporting, which cut the depth they could recurse to
from 256 KiB to 192 KiB of frames. Moderately deep recursion inside an
async body or generator then threw RangeError where Node runs it, for
example 3000 frames of an unoptimized build on arm64 macOS.
Fibers now get 512 KiB, which leaves 384 KiB after the reserve. Pages are
still committed lazily, so idle and shallow fibers cost address space, not
memory. The corpus pins recursion inside async functions and generators
next to deeper recursion on the main stack.
A reference parameter that the body rebinds made the whole parameter
owned: every caller retained the argument and the callee released it on
exit, even when the rebinding never ran. tsc-ts's isTypeRelatedTo starts
with `if (isFreshLiteralType(source)) source = ...regularType` and was the
largest single source of Type releases.
When every write is a plain statement assignment, the parameter now keeps
borrowing the caller's argument; each assigned value moves into a
separate owner slot that the next rebinding releases and replaces and
that the function scope releases on every exit. Reads use the parameter
slot, so whole-value uses still retain. Expression-position writes,
captures, loop and catch bindings, suspending bodies and string
parameters (whose in-place append needs a uniquely owned binding) keep
the owned convention. Unchanged-parameter users (stable call arguments,
aliases, frame-long element borrows) still exclude these parameters.
The call-lifetimes package test now expects `snapshot` to keep its
borrowing body: the alias saved before the rebinding still owns its value.
An edge-preserving function whose every return is a walk of its borrowed
parameters (accessors such as `node.children`, `t.types`, parent walks,
or a call to another such function) now returns its result at +0 from the
borrowing body. The result stays reachable from the arguments, so direct
callers that consume it as a receiver, a walk, or a borrowable argument
use it in place; every other direct caller tests the pending exception
and then retains it, before the argument snapshots that keep it reachable
are released. The owned adapter retains a present result (a throwing body
returns a null dummy, which string and array retains do not accept) before
releasing its parameters. Candidates borrow every reference parameter,
have no try statements and return a plain reference (instances, records,
arrays, strings, nullable-pointer unions).
Implementations of a vtable slot that borrows parameters are excluded:
virtual dispatch reaches their borrowing body (or its virtual adapter)
directly and its callers own the result. Without this, corpus 4545's
virtual accessors hit a heap-use-after-free in the sanitized lane.
The set grows to a fixpoint, since a call to a borrowed-return function
with walk arguments is itself a walk; walk facts are then recomputed with
the final set, admitting only parameters whose convention borrows.
Walk locals now cover every plain reference type, not only instances.
In tsc-ts, compareNodes -> sourceFileOf -> getSourceFileOfNode and
maybeTypeOfKind's loop over typesOf(t) no longer touch reference counts.
A parameter that is rebound only by statement assignments of walk
projections (`source = (source as LiteralType).regularType`) used to
become an owned parameter: every caller retained the argument, the callee
released it on exit, and each rebinding retained the new value and
released the old. In an edge-preserving function its incoming value is the
caller's borrow and every later value is reachable from the parameters, so
it can stay borrowed like any walk local.
The walk analysis now runs once per module before call lifetimes, which
merge these parameters into the borrowed set. Unchanged-parameter users
(stable call arguments and aliases, frame-long array element borrows)
still only see parameters that are never rebound.
tsc-ts's isTypeRelatedTo, which normalizes fresh literal types this way
on entry, no longer touches reference counts for its type arguments.
A local whose every definition projects an unwritten parameter or another
such local through plain field reads, casts, nullable narrows/wraps and
checked ternaries (the parent walk `p = p.parent`) now holds a borrowed
pointer: no retain at the definition, no release when it is rebound or
leaves scope. This is sound only in functions whose whole body preserves
heap edges (ReferenceEffects.functions): nothing they run removes a field,
element or global reference, so every object reachable from a parameter
at entry stays alive until the function returns. Whole-value uses still
retain their own copies.
The unreachable-completion fence after a `for (;;)` loop throws a fresh
constant error and preserves edges like `throw`; it used to make every
such function look mutating.
tsc-ts's getSourceFileOfNode loop did two increments and two full
decrements (with cycle-candidate checks) per parent step; it now only
loads and tests the parent pointer.
`const x = a as LiteralType` lowers to a ternary whose failing arm always
throws and whose successful arm narrows and casts the unchanged source.
The alias projects the same stable owner, so it can borrow like a plain
copy of the binding instead of retaining at the declaration and releasing
at scope exit. Call arguments of the same shape borrow too.
tsc-ts's sameLiteralValue (two casts per call, on the relation hot path)
loses all of its reference counting.
A wrap into a nullable-pointer union is the payload pointer itself (or an
immortal unit constant), so it can borrow exactly when its payload can,
as a receiver and as a call argument. tsc-ts widens many `Type` and
`Node` parameters to `T | undefined` (they may receive unchecked array
reads), so `compareTypes(c, t1, t2)` wrapped `t1` for every identity test
and call and retained and released it each time.
Required array element reads may borrow as receivers while the borrowed
array owns the element and the index preserves heap edges (array
operands already borrow; this borrows the element itself).
Reference-effect analysis now sees through switch statements, class
references, primitive formatting and virtual calls: a virtual call
preserves edges when every implementation reachable from its static class
(the inherited one plus every override below it) does. Runtime classes
keep dispatch opaque.
Native executables used to terminate with a signal when recursion
exhausted the stack. Functions that can take part in unbounded recursion
now compare the stack pointer against a per-stack guard on entry and
throw Node's `RangeError: Maximum call stack size exceeded` through the
ordinary exception path, so catch handlers, finally blocks, worker error
events and the uncaught-error exit code behave as they do under Node.
- The checked set is every function on a cycle of the call graph, where
operations that can reenter compiled code indirectly (indirect calls,
callbacks, dynamic and library operations) reach closure targets and
class members. Non-recursive functions, including leaf callbacks, stay
check-free, and the may-throw analysis accounts for the new throw.
- The runtime installs the guard per context (main thread from the stack
rlimit, workers from their thread attributes) and per async fiber, with
a reserve for the throw, unwinding and error reporting. Worker threads
now get an explicit 8 MiB stack.
- Scalar call results pass through the unwind path as its dummy value, so
calls in tail position keep tail-call and recursion elimination.
Class-typed fields that construction may read before assigning them now
observe undefined instead of reading an empty slot. A small analysis walks
field initializers and the constructor in evaluation order and stops at the
first point that can hand the instance to other code (a method call, an
argument, a callback, a base constructor that does); private helpers that
only assign fields are followed. Fields not assigned by then take the
deferred-init representation:
- the slot starts empty and reads check it inline, so assigned reads stay
borrowed and only an empty slot reaches the throw;
- equality, `typeof`, truthiness, `== null`, optional chaining, `as`
casts, undefined-admitting destinations and console output observe the
undefined itself;
- member reads, method calls, updates and writes through an unassigned
field throw Node's TypeErrors in Node's evaluation order.
Fields assigned before any exposure keep their plain representation.
Definite-assignment-asserted fields assigned through such private helpers
no longer need the deferred form either.
Corpus 4471 pins inheritance, callbacks, initializer order, private helpers
and member updates; unit tests cover the analysis and the emitted checks.
A ternary whose arms are string literals (`i === 0 ? '' : ','`) produced
an owned frame temp, so every evaluation ended with a scr_str_release call
on an immortal string. tsc-ts made 3.3M such calls (2.1M in typeListKey).
The result is an interned literal like a strLit operand: it is now marked
immortal instead of owned, so it is neither retained nor released wherever
it goes. Immortal temps are recorded per block builder, since temp names
are only unique within one.
Corpus 4564 stores, returns, captures, compares and concatenates such
choices, nested ones included.
tsc-ts self-check (two 11-run interleaved benches): 1.864 -> 1.803 s and
1.736 -> 1.706 s (-1.7..-3.3%), check -0.6% and -2.4%.
An element read (`c.nodes[i]`, `i in c.nodes`, hole tests) borrowed its
array only when it was an unchanged local; an array held in a parameter's
or local's field was retained and released around every read. tsc-ts's
getTypeAtFlowNode scans `c.sharedFlowNodes[i]` and reads the matching
`c.sharedFlowIncomplete[i]` / `c.sharedFlowTypes[i]`: 3.3M retain/release
pairs of 13.5M array releases in the self-check.
Element reads run no user code, so they now take their receiver through
emitStableReceiver like the scalar array intrinsics: a projection rooted in
a counted owner is borrowed while the index cannot remove a reference
edge; an effectful index (a call that may replace the array) keeps the
owned snapshot, so the read still sees the array named first.
Corpus 4563 covers reads through parameter and nested fields, holes and
`in`, and an index that replaces the array mid-expression.
tsc-ts self-check (median of 11, interleaved): 1.757 -> 1.715 s (-2.4%),
check 1.403 -> 1.369 s; binary -16 KB.
`s += x` (canonically `s = s + x`) on a string binding took a retained
snapshot of `s`, evaluated the suffix, released the binding's value so the
snapshot became unique, concatenated (appending in place), and released
the snapshot: a retain and two releases around every append. tsc-ts's
typeListKey alone made 3.4M such releases (plus 2.1M on literal temps).
When the binding is an unboxed local that the suffix does not mention,
nothing but this function's own expressions can read or write it, so
reading it after the suffix gives the left side's value. The old value now
moves into scr_str_concat_move / scr_str_concat_mixed_move, which consume
their head (appending in place when it is unique), and the result takes
its place in the binding: one runtime call instead of four. Boxed
bindings, suffixes that read the local, and expression-position updates
keep the general path.
Corpus 4562 covers aliases that must keep their value, literal heads,
number suffixes, throwing suffixes, self-reading suffixes, expression
position, captured bindings, and long ASCII and non-ASCII appends.
tsc-ts self-check (median of 9, interleaved): 1.854 -> 1.804 s (-2.7%),
check 1.471 -> 1.428 s.
Virtual dispatch kept the owned ABI: the caller retained every argument
and the method's owned entry released what its borrowing body did not
consume. For a visitor-style forEachChild that meant a retain and a
release of the receiver per call, and the release buffered every node the
first time a visitor reached it (1.3M cycle candidates on the tsc-ts
self-check came from forEachChild alone).
call-lifetimes proves per function which parameters its body borrows,
independent of the caller. When every implementation of a vtable slot has
a borrowing body for a parameter, the slot now borrows it: call sites pass
it like a borrowed argument of a direct call (an unchanged local as is,
anything else as an owned snapshot released after the call), and the
vtable stores the borrowing body. An implementation that borrows more
parameters than its slot gets a `.virtual` adapter that releases the
difference; closures, async methods and generators keep the owned slot.
Corpus 4561 covers visitors with early exits, a holder that drops its
own reference to the child it is visiting, slots narrowed by a captured
receiver and by a reassigned parameter (both adapters), results and
exceptions through borrowed virtual calls.
tsc-ts self-check (median of 9, interleaved): 1.788 -> 1.744 s (-2.5%),
check 1.438 -> 1.407 s; binary -55 KB.
A store of a reference-counted value always retained its receiver for the
duration of the store and released it afterwards, while scalar stores
already borrowed a stable receiver. The old value's release cannot drop a
receiver rooted in a counted owner: the owner's path to the receiver never
uses an edge leaving the receiver, and destructors run no user code. So
ref-valued (and nullable-pointer) stores now use emitStableReceiver too.
In a derived constructor `this` lowers to a sequence that throws unless
super() has returned, which no borrow check recognized: every field store,
the super() call (an upcast of `this`) and the discarded `this` result of
the super() statement retained and released the new object, and each
release left it buffered as a cycle candidate. Such throwing guards over
scalar conditions now read through to their result (guardedValue), class
casts of an unchanged local are borrowable call arguments, and a
statement-position sequence whose result is such a read drops it without a
retain (the sequence's locals still move to the statement frame).
Corpus 4560 covers released subtrees that point back at the receiver,
receivers reached through parameter fields and reassigned locals, base
constructors calling overridden methods, and super() chains.
tsc-ts self-check (median of 7, vs /tmp/tscts/tsc-int3): 1.697 -> 1.702 s
(neutral), binary 17,218,200 -> 16,768,696 bytes (-2.6%).
A literal holding a value that may be missing at run time (and the item
arrays of push/unshift/toSpliced with such values) starts from an empty
array and stores each element with a state test. The empty array had no
dense storage, so the first store always took the runtime path and grew
the array. arrayLit gains an optional capacity hint (validated: an
integer between the element count and 1024, no observable effect) that
the emitter passes to the allocation; these builders set it to the
number of plain elements, so the stores stay on the inline dense path.
tsc-ts hits this in getOptionalType's `[t, missingOrUndefined]`.
A call argument or local read from an array may skip its retain when the
enclosing function preserves every heap edge and the array is a stable
borrowed parameter. Accept pure projections of such a parameter as well
(field and record reads, narrowing, casts): the caller-owned root keeps
each projected field, the array, and its elements alive for the frame.
The edge-preservation summary rejected `??` and Math library calls,
neither of which can remove a reference edge, which disqualified
tsc-ts's compareNodes and compareCodePoints and with them the symbol and
type sort comparators. compareSymbols now passes `declarations[0]` and
the symbol names to its callees without retaining and releasing them.
`a.splice(i, n, v)` where v may hold undefined at run time (a for-of
binding or unchecked read, as in reorderCandidates) always built a
present-undefined item array. It now evaluates receiver, start, count,
and v once, in order, and branches: a present v is spliced as a plain
element literal, a missing one keeps the item array. In statement
position the emitter now also looks through such sequences and
conditionals, so the present arm drops its removed elements with
scr_arr_splice_drop and allocates nothing.
`arr.length = n` always called scr_arr_set_len, even when n already is
the length. tsc-ts resets three shared flow-cache arrays to their saved
start after every flow walk, which is usually exactly that no-op. The
emitted code now compares n with the current length first: equality is
precisely the case the runtime accepts and leaves unchanged (-0 included,
NaN never), so only real resizes and invalid lengths reach the runtime.
A statement-position `a.splice(start, deleteCount, ...items)` built a
one-element (or n-element) items array, then scr_arr_splice_insert built
the removed-elements array that the caller released straight away: three
or more allocations per sorted insert in tsc-ts's insertType. When the
result is discarded and the items are plain evaluated values, the emitter
now evaluates receiver, start, count, and items in order and calls
scr_arr_splice_drop with the owned value slots. It applies the same
clamping and state shifts on dense receivers, releases removed values
only after the receiver is consistent again, and keeps the general
implementation for sparse receivers and sparse-sized results.
The runtime-optional `x instanceof C` lowering copied C into an owned
temporary before testing. For a capture-free class reference that value
is the immortal static class object, and the copy cost an out-of-line
scr_classobj_retain_v/release_v pair on every test (2,513 sites in
tsc-ts, mostly AST accessors such as getName and getText). The class
reference is now used directly.
`a.push(v)` where v may hold undefined at run time (an unchecked array
read or a hole-observing for-of binding, as in tsc-ts's filterType loop)
built a temporary one-element array, stored v or present undefined into
it, and spread it onto the receiver: an allocation, a growth, a copy and
two releases per append. Such pushes now evaluate every argument first,
then append each present value through the ordinary push (and its inline
dense fast path) and each missing one as a present-undefined slot at the
current length, which is what Node stores. Pure receivers and arguments
are re-read instead of copied into owned temporaries.
Call arguments read from arrays of nullable references now take the
inline dense lookup like other projections (the value is the element
pointer itself, so the path is a few loads), and scr_arr_peek_ref answers
dense in-range indices before the general lookup. compareSymbols'
`declarations[0]!` arguments no longer leave compiled code.
String construction copied every span with a libc memcpy call, and
scr_str_new scanned the copied bytes for ASCII in a second pass. Spans of
at most 16 bytes (identifiers, map keys, number text) now move as two
overlapping fixed-size words, and scr_str_new tests those same words for
ASCII, so the fact is free for short strings; longer spans keep the bulk
copy and a chunked scan that stops at the first non-ASCII byte.
A scan that proves a heap string ASCII now also drops its index-cache
entry: a proven-ASCII string never owns one, because every UTF-16 mapper
answers it by identity and re-checks the header bit after extending an
index. Releasing such a string therefore skips the cache purge, and a
large text proven ASCII once (a JSON document's length, a source file)
no longer keeps every later string release walking the cache. Immortal
strings cannot record the bit and keep their entries as before.
buf.write(string, 'utf16le' | 'latin1' | 'ascii') decoded one UTF-8
code point per step. tsc-ts converts every source file to UTF-16 this
way (toCodeUnits), so the per-character loop showed up in the profile.
Eight-byte ASCII runs whose units all fit the remaining budget are now
widened (utf16le) or copied directly; any other position, and a tail
that would cross the budget, takes the unchanged per-code-point path, so
truncation at a unit or surrogate boundary is exactly as before.
JavaScript string reads use UTF-16 indices over scriptc's UTF-8 storage,
so charCodeAt, length, slice, substring and indexOf looked every receiver
up in a small global index cache (scr_sidx) on each call, and a fresh
short receiver evicted an entry and rescanned its bytes. In the tsc-ts
self-check that lookup and its mapping were the largest string cost.
Bit 31 of the capacity word now records that a string is proven all
ASCII, where units are bytes. A clear bit means "not known", so the fact
only needs to be exact where it is set: scr_str_new and its users prove
it while copying, concatenations combine their operands' bits, number
text, ASCII slices and repeat inherit it, emitted literals and runtime
statics carry it in their capacity word, and an index-cache scan that
proves ASCII records it. scr_str_hash_forget clears it with the cached
key hash, so every in-place mutation drops it; an in-place append that
keeps the string ASCII sets it again. Capacity stops at 2^31 - 1 bytes,
still above the UTF-8 size of any string V8 can represent.
Proven-ASCII receivers skip the index cache in every UTF-16 mapper. Sites
for length and charCodeAt call small internal helpers (string-reads.ts)
that LLVM inlines: a header load and, for an in-range index, one byte
load; everything else defers to the runtime with unchanged semantics.
For non-ASCII receivers the cache remembers its last hit (validated by
owner and tier), charCodeAt answers sequential scans from the cached
ASCII span before any other work, and appends that keep a string ASCII
no longer walk the cache.
`s + n`, multi-part concatenations with number operands, and `s += a + n`
materialized each number as a temporary heap string, and a compound
suffix as a second string, before copying them into the result. A new
runtime entry, scr_str_concat_mixed, takes string and number operands
together and formats numbers directly into the result. Given a head, it
follows scr_str_concat's left-operand rule: appended in place when the
caller's borrow is its only reference, it has room, and it is not also an
operand.
The self-concatenation assignment now flattens its suffix and appends
every operand to the snapshot in one call, so tsc-ts's typeListKey loop
(`key += (i === 0 ? '' : ',') + types[i].id`) appends in place without
allocating per element. Operands still evaluate left to right; converting
a number has no effects, so formatting it at the call keeps JavaScript
order. A corpus program pins Number::toString shapes, evaluation order,
self-referencing suffixes, aliases taken mid-append and Unicode text.
Maps and Sets with number keys used as id tables (tsc-ts keeps node and
symbol links in Map<number, Links>) hashed every key as a double. They now
keep a direct index, dense[k] = entry index + 1, while every live key is an
integer in [0, ndense) and the table stays within 8x the live count (64
slots minimum). The entries array, tombstones and iteration order are
unchanged; only the lookup index differs.
-0 lands on slot 0 (SameValueZero), and NaN, fractions, negatives and keys
beyond the table are absent by construction. Inserting a key the table
cannot hold moves the map to the bucket table; whenever that table would
grow, compact integer keys move it back, so maps whose ids start far from
zero switch over once their live count catches up. scr_map_entry_f64 and
layout asserts expose the index to generated code.
A randomized C test compares every operation with an ordered reference
model across linear, direct and hashed indexes, and a corpus program pins
the JavaScript-visible semantics around the transitions.
Only growth moves a map to the direct index: an append that
scr_map_reserve_append would absorb by compacting tombstones (a linear map
with a dead entry, a bucket table at most half live, no iteration active)
keeps the map's compact storage, so churn on a small number-keyed map no
longer allocates a table. While an iteration is active nothing compacts,
so a small map promotes to the direct index (integer keys) or the bucket
table (other numbers) without moving entry indices. The runtime map test's
small-storage script, which assumed bucket promotion and failed its two
live-iteration checks, now runs with integer and fractional keys and
checks both transitions, and the corpus program covers small maps growing
and clearing mid-iteration.
A local captured by a closure lives in a box shared by its declaring
function and every capturing closure, so the range analysis had no facts
for it anywhere, not even in the declaring function. int32-slots.ts now
groups the members of each box (closure captures map positionally onto
the lifted function's captures) and proves the group int32 when every
write to it anywhere is proven and it starts from a proven parameter or
an initialized declaration; ++/--, for-of and catch bindings, TDZ boxes
and class-captured bindings stay unknown. analyzeIntegerRanges reads the
proof through a new boxed-binding fact.
Corpus 4453 adds closures that read an int32 parameter, store a fraction
into a captured local, and count past int32.
A whole-program optimistic fixpoint (ir/int32-slots.ts) proves which
number-typed class fields only ever hold int32 values (never -0, NaN, a
fraction or an out-of-range integer), which parameters of directly called
functions receive an int32 at every call site, and which results are int32
on every return. It reuses analyzeIntegerRanges per function under the
current facts and re-analyzes readers of any disqualified slot.
Proven fields are stored as i32. Reads yield the i32 as the value's
integer view (bit tests and comparisons use it directly) and its exact
widening as the double, so every observation, including dyn views, JSON
and inspect, prints identically. Writes store the proven integer.
Parameter and result ABIs stay double; their facts only remove coercions.
Writes the IR does not show are excluded: fields that a dynamic store in
the program can name on a class reaching checked-dynamic code (live views
commit stores back), runtime-rooted and generic classes, ++/-- on the
field, and parameters of escaping, class-value-constructed or virtually
dispatched functions. Library and worker builds are untouched. The dyn
commit adapter traps rather than store a non-int32 into an i32 field.
In tsc-ts, Type.flags/objectFlags, Symbol.flags/checkFlags,
Signature.flags and ~100 other fields become i32; isSimpleTypeRelatedTo
drops from 1489 to 436 instructions and from 83 floating-point
conversions to none.
Corpus 4451-4453 pin field storage edge cases (overflow into doubles,
-0, NaN, fractions, uint32, subclass writes, enum members and reverse
mappings, JSON/inspect through live views, union discriminants), dynamic
stores (named, computed, Object.assign, Reflect.set, defineProperty), and
int32-closed locals, parameters and results; preflight/order baselines
recorded for all three.
`x as Sub` lowered to a call to an interned %class.assert helper that
unwrapped a union box, retained the payload twice, compared the class-id
range, and threw on mismatch; every use paid a call, three retains, two
releases and a pending check (2,152 sites in tsc-ts). Plain operands
(locals and field reads, which isSafeToRepeat already admits) now lower
to the check itself: per compatible union arm a tag test plus, where the
arm is not already the target or a subclass, an instanceOf range test,
selecting the downcast payload, with the helper's exact TypeError as the
final arm. Other operands keep the helper so they are evaluated once.
The backend borrows through the result: instanceOf reads its operand as
a receiver instead of retaining a temporary, and downcast/upcast are
borrowable, edge-preserving projections, so `(node as Sub).field` and
method receivers on a cast no longer touch reference counts. The mismatch
arm unwinds directly (previous commit) and stays out of the hot path.
Corpus 4432 pins the Node-observable behavior of failing casts (a
TypeError before any later read, unwinding through finally blocks and
callbacks) and of successful casts from bases, subclasses and unions; a
harness test pins the exact messages, which Node cannot oracle.
main's emitPendingCheck (#785) already tests `scr_exc_active->kind`
inline after every may-throw call in executables. The helper and adapter
bodies the backend generates (dyn check helpers, async/generator
trampolines, inline-async wrappers, FFI callback adapters, island and
stream adapters, IPC message thunks, dynamic-key record stores) still
called `scr_exc_pending()`, an opaque call into the prebuilt runtime,
and so did every runtime C unit. On the tsc-ts self-check that function
was about 4% of self time.
Those sites now share pendingTestLines, which follows emitPendingCheck's
policy: executables load the active cell and compare its i32 kind
inline; libraries and worker programs keep the runtime call (workers
also observe cross-thread termination there). Runtime units outside
thread-instanced libraries and worker executables get the same inline
test through a scr_runtime.h macro; the exported scr_exc_pending
definition stays for those lanes and for emitted slow paths. A static
assert pins the i32 kind at offset 0.
This replays the work item's inline-check commit on top of #785: its own
emitPendingCheck rewrite is dropped in favor of main's.
Adds corpus 4431 pinning exception propagation across fiber switches,
generators, sort/map callbacks, and runtime JSON failures.
Two corpus programs from the dropped tenuring work, reworded for main's
three-generation collector: a tree with parent back edges ages into the
old generation and then loses subtrees as dead cycles (plus temporary
trees held across passes inside a call), and weak collections keyed by
objects that age into the old generation and later die inside cycles.
Only full passes reclaim either, so the sanitized lane's exit RC audit
proves they are reclaimed rather than leaked, and the outputs pin that
live structure and live weak entries survive every pass in between.
`a === b` on references and `x instanceof C` only read pointers (and the
vtable word), yet each operand was retained before the compare and
released after it. Use borrowableInputs for both, which keeps
left-to-right evaluation and falls back to an owned operand whenever a
later operand might release it. A corpus program pins that fallback with
an operand whose freed block the next allocation reuses.
tsc-ts self-check (median of 7): 3.06s -> 3.00s; binary -249 KB.