Repository navigation
fix(runtime): pass a TypeScript constructor's arguments to the Java constructor - #2147
Conversation
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
…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".
bac3f0f to
53753ce
Compare
…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 -->
Description
TypeScript compiles a class without its own constructor (and
super(...args)at ES5 targets) to:For native base classes,
__extendsininternal/ts_helpers.jsreplacesParent.apply. That helper built the constructor's argument list as[null].concat(args).concatspreads arrays but not anargumentsobject, so the Java constructor got one argument, theArgumentsobject, instead of the values passed tonew. Creating such a class with any argument threwCannot marshal JavaScript argument. Created with no arguments, it worked, because that path skips the list.The helper now copies
argswithArray.prototype.slice.call(args)before concatenating, which handles both an array and anargumentsobject.Does your commit message include the wording below to reference a specific issue in this repo?
No.
Related Pull Requests
Parent.applyline (it constructs withReflect.constructand no longer makes the instance a prototype), but keeps[].concat(args), so it still has this bug. Whichever of the two merges second needs a one-line rebase toReflect.construct(Extended, Array.prototype.slice.call(args)).Does your pull request have unit tests?
Yes.
testsForTypescript.jsadds "When_a_typescript_class_without_a_constructor_is_created_with_arguments_it_should_pass_them_to_the_java_constructor": TypeScript's output forclass NamedThread extends java.lang.Thread {}, created with"named"(checksgetName()) 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