Skip to content

feat: Node-style primordials for runtime builtins - #415

Open
edusperoni wants to merge 1 commit into
feat/js-builtinsfrom
feat/primordials
Open

feat: Node-style primordials for runtime builtins#415
edusperoni wants to merge 1 commit into
feat/js-builtinsfrom
feat/primordials

Conversation

@edusperoni

@edusperoni edusperoni commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator

Stacked on #411 — review that one first; this PR targets feat/js-builtins.

What this adds

The runtime's builtin JavaScript installs globals and leaves closures behind that run for the lifetime of the app: event dispatch, the Promise proxy traps, console's smart-stringify, __extends, the URL.searchParams accessor. Until now those closures reached for intrinsics (Array.prototype.slice, JSON.stringify, Object.create, …) through the live globals, so app code replacing one could break runtime internals or observe them.

NativeScript/runtime/js/primordials.js is a new builtin that captures exactly the intrinsics the other builtins need into a frozen, null-prototype namespace, Node-style.

The (binding, primordials) contract

Builtins are now compiled as function bodies with two fixed parameters:

const { someNative } = binding;
const { ArrayPrototypeSlice, ObjectCreate } = primordials;

primordials is built lazily on the first RunBuiltin of an isolate — which happens during runtime init, before any user code — and cached in Caches::Primordials. Consequences:

  • Worker isolates snapshot their own realm's intrinsics automatically.
  • Builtins that compile late still get the pristine snapshot. smart-stringify is only compiled on the first object logged, which can be well after user code has run.
  • binding is unchanged; most builtins still receive undefined for it.
  • The bytecode cache stays sound: it is process-local and in-memory only, and every compile in a process now uses the same 2-parameter signature.

Why uncurrying, uniformly

Instance methods are exposed uncurried, exactly as Node does it:

const uncurryThis = Function.prototype.bind.bind(Function.prototype.call);
// ArrayPrototypeSlice(list, 1)          not  list.slice(1)
// FunctionPrototypeCall(cb, this, ev)   not  cb.call(this, ev)

The runtime always runs V8 jitless on device, so the usual "uncurrying is free once optimized" argument does not apply and the cost had to be measured. Benchmarked on Node 24 / V8 13.6, arm64 host, --jitless:

  • Uncurried primordial call: +5-12% per op versus a raw method call.
  • For event dispatch that is ~+10%, about 26 ns on a 4-listener dispatch — irrelevant next to the listener bodies.
  • Under Ignition, uncurried beats the captured.call(recv, …) alternative, which is why uncurrying is used uniformly rather than mixing styles.
  • Captured statics (JSON.stringify etc.) are free.
  • Reflect.apply is measurably worse and is not used; FunctionPrototypeApply covers those sites.

Plain constructor calls made once at init time (new Map() while bootstrapping) may stay direct — the rule targets code in closures that outlive init.

Enforcement

eslint.config.mjs declares primordials and adds two rules over NativeScript/runtime/js, both verified to fire:

  • no-restricted-properties for every captured static (JSON.stringify, Object.defineProperty/assign/freeze/create/keys/setPrototypeOf/getOwnPropertyDescriptor, Array.from, Reflect.construct, Reflect.apply).
  • no-restricted-globals for every captured constructor (Error, Map, Proxy, TypeError). A const { Proxy } = primordials destructure shadows the global, so the rule only fires on an unguarded reference.

Each message names the replacement. primordials.js itself is exempted via a per-file override. Uncurried instance-method use cannot be matched by receiver, so that stays a review rule — documented as such in NativeScript/runtime/js/README.md.

Deliberately left as live global lookups: Reflect.decorate in inline-functions.js (reflect-metadata installs it after runtime init, and the TypeScript __decorate shim must see it), Blob/File in blob-url.js (provided by the app layer, not the runtime), and String(x)/instanceof Array conversions where tamper-immunity is not affected.

ts-helpers builds native super calls with the captured Reflect.construct rather than bind-then-new, which keeps that path off the array iterator protocol as well.

Tests

New TestRunner/app/tests/PrimordialsTests.js (7 specs) tampers with the intrinsics and checks the runtime keeps working. Each spec keeps the tampered window synchronous and assertion-free, restoring the originals in a finally:

  • a guard spec proving the tampering is actually observable, so the suite cannot pass vacuously
  • global dispatchEvent delivers to every listener (function and handleEvent) with Array.prototype.slice/indexOf/push/splice and Function.prototype.call replaced
  • addEventListener/removeEventListener and once semantics under the same tampering
  • reportError still reaches an error listener with a correct ErrorEvent
  • console.log of a circular object stays non-fatal with JSON.stringify and the replacer's Array.prototype.indexOf/push replaced (the smart-stringify path; its output is not reachable from JS and JsonStringifyObject swallows a throwing stringify, so this spec is a crash/throw check rather than an output assertion — noted in the test)
  • a native _super.call(this, x) over an Objective-C base with Array.prototype.slice/concat, Function.prototype.bind and Reflect.construct replaced
  • __extends and __tsEnum with the Object statics replaced

Result: 912 specs, 0 failures (905 baseline + 7), independently reproduced on a second simulator. ESLint clean; every builtin verified to compile as a (binding, primordials) function body.

Known follow-ups (not in this PR)

Pre-existing live-intrinsic reads that primordials does not yet cover: for...of ObjectKeys(...) in __tsEnum and ArrayFrom(arguments) in inline-functions.js still go through the array iterator protocol, and String(x) conversions in events.js/error-events.js read the live global String.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 05ac701e-c0f5-4bf0-a01d-36e62461d75d

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • ✅ Review completed - (🔄 Check again to review again)

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

Comment @coderabbitai help to get the list of available commands.

@edusperoni
edusperoni force-pushed the feat/primordials branch 2 times, most recently from e31477b to bce9ece Compare July 30, 2026 14:17
@edusperoni

Copy link
Copy Markdown
Collaborator Author

Orchestrator review pass (folded into the commit):

  • Independently verified the Reflect.construct switch in ts-helpers (bound-function newTarget semantics and the arguments-object concat edge both hold) and every other conversion.
  • Closed the two flagged coverage gaps: String is now a captured primordial (used by the Event/ErrorEvent constructors and dispatch closures), and the two post-init paths that depended on the tamperable array-iterator protocol — __tsEnum's for...of and the ObjC decorators' Array.from(arguments) — now use index loops. Array.from deliberately has no primordial; the ESLint config documents why and restricts String as a global.
  • Suite after changes: 912/912.

Deferred (pre-existing, unchanged by this PR): child[Symbol.hasInstance] = ... in ts-helpers is likely a silent no-op in sloppy mode (inherited non-writable Function.prototype[@@hasInstance]), and instanceof Array in ObjCClass could become ArrayIsArray — both worth their own look since fixing them changes behavior.

@edusperoni
edusperoni marked this pull request as ready for review July 30, 2026 17:20
The runtime's builtins install globals and leave closures behind that keep
running for the lifetime of the app: event dispatch, the Promise proxy traps,
console's smart-stringify, __extends. Those closures reached for intrinsics
(Array.prototype.slice, JSON.stringify, Object.create, ...) through the live
globals, so app code replacing one could break or observe runtime internals.

primordials.js captures the intrinsics the other builtins need into a frozen,
null-prototype namespace and BuiltinLoader passes it to every builtin as a
second fixed parameter next to `binding`. It is built lazily on the first
RunBuiltin of an isolate — during runtime init, before user code — and cached
in Caches, so workers snapshot their own realm and late-compiling builtins
still see pristine intrinsics.

Instance methods are uncurried Node-style, `uncurryThis(fn)` being
Function.prototype.bind.bind(Function.prototype.call): ArrayPrototypeSlice(list, 1)
rather than list.slice(1). Benchmarked under jitless (which is how the runtime
always runs on device) uncurried calls cost +5-12% per op over a raw method
call but beat the captured-and-.call() alternative, so they are used uniformly.

ESLint gains no-restricted-properties for the captured statics and
no-restricted-globals for the captured constructors, each pointing at the
replacement; uncurried instance-method use stays a review rule since the
receiver cannot be matched.
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.

2 participants