Skip to content

fix(runtime): pass a TypeScript constructor's arguments to the Java constructor - #2147

Merged
edusperoni merged 1 commit into
mainfrom
fix/ts-apply-arguments
Nov 22, 2026
Merged

edusperoni merged 1 commit into
mainfrom
fix/ts-apply-arguments

Conversation

@edusperoni

@edusperoni edusperoni commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Description

TypeScript compiles a class without its own constructor (and super(...args) at ES5 targets) to:

function NamedThread() {
    return _super !== null && _super.apply(this, arguments) || this;
}

For native base classes, __extends in internal/ts_helpers.js replaces Parent.apply. That helper built the constructor's argument list as [null].concat(args). concat spreads arrays but not an arguments object, so the Java constructor got one argument, the Arguments object, instead of the values passed to new. Creating such a class with any argument threw Cannot marshal JavaScript argument. Created with no arguments, it worked, because that path skips the list.

The helper now copies args with Array.prototype.slice.call(args) before concatenating, which handles both an array and an arguments object.

Does your commit message include the wording below to reference a specific issue in this repo?

No.

Related Pull Requests

Does your pull request have unit tests?

Yes. testsForTypescript.js adds "When_a_typescript_class_without_a_constructor_is_created_with_arguments_it_should_pass_them_to_the_java_constructor": TypeScript's output for class NamedThread extends java.lang.Thread {}, created with "named" (checks getName()) and with no arguments.

The full suite (arm64 emulator, android-36.1 google_apis image) passes on this branch: 1789 specs, 0 failures.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed constructor argument handling for TypeScript-defined subclasses of Java threads. Arguments are now correctly passed to the Java constructor, allowing thread names to be set as expected. Instances created with or without arguments are also correctly recognized as instances of the subclass.

@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Parent.apply now passes a sliced copy of its arguments to the bound constructor. A TypeScript test checks a java.lang.Thread subclass created with and without an argument.

Changes: Subclass construction

Layer / File(s) Summary
Bind subclass constructor arguments
test-app/app/src/main/assets/internal/ts_helpers.js, test-app/app/src/main/assets/app/tests/testsForTypescript.js
Parent.apply passes a sliced copy of args to the bound constructor. The test checks instance identity with and without an argument and verifies that getName() returns "named".

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: vtrifonov

Merge Risk: Minimal · up to 53753

TypeScript subclasses without their own constructor now pass constructor arguments to the Java constructor instead of failing to marshal an Arguments object. The change is small and tested, and no merge-blocking risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the primary change: the runtime helper now forwards a TypeScript constructor's arguments to the Java constructor. The raw summary and objectives both describe a fix in internal/ts_help…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the primary change: the runtime helper now forwards a TypeScript constructor's arguments to the Java constructor. The raw summary and objectives both describe a fix in internal/ts_helpers.js that converts the arguments object to an array before concatenation, plus a test for a TypeScript class without an explicit constructor. The title is specific, follows the conventional commit style, and matches the changeset.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 2cb821d and 53753ce.

Files selected for processing: 2

  • test-app/app/src/main/assets/app/tests/testsForTypescript.js
  • test-app/app/src/main/assets/internal/ts_helpers.js

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.

…onstructor

TypeScript compiles a class without a constructor to
`_super.apply(this, arguments) || this`. The helpers concatenated the
arguments object into the argument list instead of its elements, so the
Java constructor received a single Arguments object and creating the
instance with any argument threw "Cannot marshal JavaScript argument".
@edusperoni
edusperoni force-pushed the fix/ts-apply-arguments branch from bac3f0f to 53753ce Compare November 22, 2026 21:22
@edusperoni
edusperoni merged commit 7546ca1 into main Nov 22, 2026
11 checks passed
@edusperoni
edusperoni deleted the fix/ts-apply-arguments branch November 22, 2026 21:39
edusperoni added a commit that referenced this pull request Nov 23, 2026
…de (#2148)

### Description

Creating an instance of a TypeScript class that extends a Java class
(`class X extends android.view.View`, compiled to ES5 with `__extends`)
costs several times more than the same class made with `.extend()`. Most
of that comes from how `internal/ts_helpers.js` builds the instance.

**Root cause.** For native base classes, `__extends` replaces
`_super.call`/`_super.apply`. The replacement created the Java-backed
instance, then set it as the prototype of the constructor's own `this`
(`thiz.__proto__ = native`). In V8, setting an object as a prototype
switches it to **prototype mode** and gives it a map of its own. So
every instance ended up with a unique map:
- each field the constructor stores (`_this.a = ...`) misses its inline
cache and copies the map, about 1.4 µs per field;
- the switch itself adds about 7 µs of fixed overhead per instance.

This happens in every wrapper-lifetime mode, and later property access
on the instance pays for the unshared map too.

**Change.** The helper now builds the instance with `Reflect.construct`
and never makes it a prototype. It stores the instance under a private
symbol on the constructor's `this`, and `__native` looks for it there.
TypeScript 2+ output (`var _this = _super.call(this, ...) || this; ...;
return _this;`) uses the instance `super()` returns directly, so it
behaves as before. `Reflect.construct` also replaces the
`Function.prototype.bind.apply` construction.

#### Not supported any more: pre-TypeScript 2 constructor shapes
TypeScript 1.x emitted `_super.call(this)` without using its result, and
kept working on its own `this`. That `this` used to reach the Java
instance through its prototype; it no longer does.
- A constructor that ends with `return __native(this)` still works:
`__native` moves the fields set on `this` to the instance and returns
the instance. The existing specs in `testsForTypescript.js` that use
this shape still pass.
- Between `_super.call(this)` and `__native(this)`, calling Java methods
on `this` or passing `this` to Java no longer works.
- A constructor that returns neither `__native(this)` nor the instance
gets back a plain JS object, not the Java instance.

#### Measurements
Samsung SM-G780G (Android 13). Optimized release APKs (`-Poptimized
-Prelease -Pabis=arm64-v8a`), built with a local benchmark harness (not
part of this PR).
- **Labels:** `BASE` = the previous helpers; `STASH` = this branch's
helpers. Both APKs contain the same `libNativeScript.so`; only
`internal/ts_helpers.js` differs. `BASEb` is the `BASE` APK under a
second label, as an A/A control.
- **Procedure:** every label was reinstalled and speed-compiled each
round (`cmd package compile -m speed -f`), the first launch after each
install was discarded, and label order rotated by round. Each cell is
the median over launches of the per-launch median.
- **Where measured:** on the wrapper-lifetime stack (#2125–#2128 and
#2130), not on `main`, so canary mode can be compared. `resurrecting` is
the default mode; canary/all is the mode where every wrapper gets a
canary.

**First run: construction (6 rounds)**, µs per instance, for 1/3/5
fields set in the constructor. The floor is the same class built with
`.extend()` and the same fields.

| row | mode | BASE | STASH | `.extend()` floor |
|---|---|---|---|---|
| construct | resurrecting | 13.9 / 17.5 / 19.5 | **4.1 / 5.1 / 4.9** |
3.7 / 3.7 / 3.7 |
| construct + JS call + Java→JS | resurrecting | 21.3 / 24.0 / 26.5 |
**8.2 / 9.4 / 9.2** | |
| construct | canary/all | 18.5 / 22.3 / 25.4 | **7.0 / 10.2 / 12.3** |
6.7 / 8.0 / 10.0 |
| construct + JS call + Java→JS | canary/all | 25.5 / 30.6 / 33.9 |
**12.4 / 16.0 / 18.0** | |

A/A (`BASEb` vs `BASE`) on these rows stayed within ±6%, except
resurrecting construct with 5 fields at +12%. On every TS row the STASH
range does not overlap the pooled BASE + BASEb range. The `.extend()`
rows, which this change does not touch, moved by less than 1.5%.

**Second run (4 rounds resurrecting, 5 rounds canary/all)**, taken later
with the same APK pairs. From one round to the next, absolute numbers
moved by up to 1.7× for every label, the unchanged rows included, so
this run is reported as **STASH/BASE ratios within a round**: median
[min–max] over rounds. A/A is BASEb/BASE in the same rounds. In
canary/all round 1, three STASH launches were lost to another process on
the device; a fifth round makes up for them.

*Construction* reproduces the first run. STASH/BASE for 1/3/5 fields;
canary/all with [min–max] over its 5 rounds:

| row | resurrecting | canary/all |
|---|---|---|
| construct, TS class extending a test Java class | 0.29 / 0.29 / 0.25 |
0.39 [0.37–0.64] / 0.47 [0.46–0.76] / 0.49 [0.48–0.77] |
| construct, TS class extending `java.lang.Object` | 0.30 / 0.27 / 0.22
| 0.42 [0.37–0.44] / 0.43 [0.41–0.49] / 0.46 [0.43–0.53] |
| construct + JS call + Java→JS | 0.43 / 0.39 / 0.33 | 0.59 [0.47–0.82]
/ 0.59 [0.50–0.88] / 0.57 [0.55–0.85] |
| A/A, first row | 0.96 / 0.98 / 0.96 | 1.02 [0.96–1.84] / 1.05
[0.99–1.78] / 0.98 [0.95–1.72] |
| `.extend()` construct (control) | 1.01 / 1.00 / 0.99 | 0.99 / 0.97 /
0.95 |

In canary/all the test-class rows are bimodal from launch to launch, for
every label: 1-field construction ran at about 17 or 29 µs with BASE and
about 7 or 11 µs with STASH. The wide ranges and the A/A of 1.7–1.8 come
from rounds where two labels landed in different modes. The
`java.lang.Object` row is not bimodal.

*Steady-state access* on 64 already-built instances, cycled. Rows:
reading 3 expandos; overwriting 3 existing expandos; a JS method; a Java
method (`hashCode()`); a Java → JS call reading `this.owner` 1 time and
15 times. Each row runs on TS `__extends` instances and on `.extend()`
instances. ns per operation, medians over rounds, resurrecting:

| row | TS, BASE | TS, STASH | TS STASH/BASE (A/A) | `.extend()`, clean
launch, BASE → STASH |
|---|---:|---:|---|---:|
| expando read ×3 | 28.4 | **4.2** | **0.15** [0.14–0.16] (1.06
[0.99–1.11]) | 5.0 → 4.7 |
| expando write ×3 | 30.6 | **4.8** | **0.18** [0.15–0.26] (0.97
[0.90–1.05]) | 5.5 → 5.5 |
| JS method call | 29.3 | **5.7** | **0.20** [0.19–0.25] (0.99
[0.96–1.10]) | 5.6 → 5.8 |
| Java method call | 427 | 398 | 0.94 [0.92–1.02] (1.00 [0.99–1.00]) |
393 → 396 |
| Java → JS, 1 read | 2231 | 2481 | 0.97 [0.82–1.81] (0.96 [0.86–1.88])
| 2523 → 2550 |
| Java → JS, 15 reads | 2552 | 2580 | 0.87 [0.74–1.57] (0.94
[0.86–1.77]) | 2576 → 2620 |

- **Resurrecting.** With the old helpers each TS instance had a map of
its own, so property and method access sites that see many instances
went megamorphic: ~29 ns for what costs ~5 ns on a `.extend()` instance.
With this change TS instances access at `.extend()` speed. The Java
method row and both Java → JS rows are within noise. The Java → JS rows
are dominated by the call itself (~2.5 µs) and are bimodal across
launches.
- **Shared code.** The `.extend()` column above comes from launches that
only touch `.extend()` instances. When the same loops first ran over TS
instances in the same launch, the `.extend()` instances paid for the
polluted inline caches: with the old helpers, 29.6 / 29.1 / 39.0 ns for
read / write / JS call. With this change they paid 10.1 / 6.8 / 6.1 ns.
So the old helpers also slowed down other objects that share code with
TS-extended instances.
- **Canary/all.** No steady-state row moved beyond noise. Medians:
expando read 0.89, write 0.95, JS call 0.83, Java call 0.98, Java → JS
1.01–1.03. Per-round A/A on these rows reached 1.35–1.87. Here, reads
cost about 20–30 ns and writes about 550–890 ns with either helper and
either kind of instance. The clean-launch `.extend()` control is flat
(1.03 / 1.00 / 1.01 / 0.99). The first run's "use a built TS instance"
row in canary/all showed STASH +40% on medians, but its launches were
bimodal (1.4–3.0 µs in every label) and the ranges overlapped. These
rows show no such regression.

#### Follow-up (not in this PR): ES classes and decorators
Native ES classes (`class X extends android.view.View` without
down-leveling) can skip the helper entirely. That needs:
- **Runtime**
- `ClassConstructorCallback` handles `new.target`: it resolves the
extended class (and caches it), uses `new.target.prototype` as the
implementation object, and calls `RegisterInstance` on the receiver.
- `CreateExtendedJSWrapper` and the canary rebuild use the class's own
prototype.
  - The profiler's `Wrap()` forwards `new.target`.
- The static binding generator recognises `class X extends <native
class>`.
- **Core**
  - An Android `NativeClass` decorator.
- Enable `isNativeESClassesEnabled` for Android in
`packages/vite/helpers/nativeclass-transform.ts` and in the webpack
equivalent.

### Does your commit message include the wording below to reference a
specific issue in this repo?
No.

### Related Pull Requests
- #2147 fixes `_super.apply(this, arguments)` dropping the arguments
(`[null].concat(arguments)` passes the `Arguments` object itself). This
PR rewrites the same `Parent.apply` line but keeps `[].concat(args)`, so
it does not fix that. Whichever merges second needs a one-line rebase to
`Reflect.construct(Extended, Array.prototype.slice.call(args))`.
- The measurements above were taken on the wrapper-lifetime stack
(#2125–#2128, #2130). The helper change does not depend on it: this
branch is based on `main`.

### Does your pull request have [unit
tests](https://github.com/NativeScript/NativeScript/blob/master/running-tests.md)?
Yes. `tests/testTypeScriptExtendedConstruction.js` (registered in
`mainpage.js`) covers TypeScript's ES5 output for a class extending a
Java class:
- `instanceof` the class and every Java class above it;
- one prototype chain shared between instances;
- field initializers kept as own properties, and per-instance state;
- JS overrides called from Java with the instance as `this`;
- `super` calls into the Java implementation;
- inherited Java methods, and passing the instance to Java and back;
- statics;
- prototype chain and expandos of a Java-held instance after a
collection;
- constructors that forward their arguments with `apply` (a class
without a constructor, and `super(...args)`).

The full suite (arm64 emulator, android-36.1 google_apis image, default
`resurrecting` mode) passes on this branch: 1798 specs, 0 failures.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Improvements**
* Improved compatibility between JavaScript subclasses and native button
classes, including constructor argument forwarding, inherited methods,
and independent instance state.
* **Tests**
* Added coverage for subclass inheritance, JavaScript and native method
dispatch, constructor behavior, and preserving native instances after
garbage collection. The new test suite is included in the main page’s
test sequence.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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