Skip to content

fix(runtime,codegen): #5894 — x instanceof <non-constructor namespace> throws TypeError - #5971

Merged
proggeramlug merged 1 commit into
mainfrom
fix/t262-5894-instanceof-noncallable
Jul 4, 2026
Merged

proggeramlug merged 1 commit into
mainfrom
fix/t262-5894-instanceof-noncallable

Conversation

@proggeramlug

@proggeramlug proggeramlug commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

1 instanceof Math (and JSON/Reflect/Atomics) must throw a TypeError — these namespace objects have no [[Call]]/[[Construct]], so InstanceofOperator rejects them regardless of the LHS.

Perry's static-instanceof codegen mapped an unrecognized RHS name to class_id = 0, and js_instanceof(_, 0) folds to false (the #585 class_id == 0 guard). So 1 instanceof Math wrongly returned false instead of throwing. (The dynamic RHS path — 1 instanceof (Math as any) — already threw correctly; only the statically-folded bare-identifier form was wrong.)

Fix

  • Runtime: add js_instanceof_noncallable_rhs() — throws TypeError: Right-hand side of 'instanceof' is not callable, honoring the existing SUPPRESS_INSTANCEOF_RHS_THROW scope used by the Symbol.hasInstance helpers.
  • Codegen: when the bare-identifier RHS is a known non-constructor built-in namespace (Math/JSON/Reflect/Atomics) and isn't shadowed by a user class, emit that helper instead of the js_instanceof(_, 0) fold. The LHS is still lowered first, so its side effects run.

Before / after (language/expressions/instanceof)

pass 29 → 30, same other failures (zero regressions). Fixed: S11.8.6_A6_T2 (1 instanceof Math).

Verified normal usage is untouched: b instanceof B/A/Object, [] instanceof Array, new Error() instanceof Error all still true.

The remaining instanceof failures (F.prototype not an object; Function.prototype as RHS; getter side effects) are a separate, more involved root in js_instanceof_dynamic and are out of scope here.

Validation

  • cargo fmt --all -- --check clean; check_file_size.sh OK.

Refs #5894. Code-only per contributor guidance.

Summary by CodeRabbit

  • Bug Fixes
    • instanceof now handles built-in namespace objects like Math, JSON, Reflect, and Atomics correctly.
    • Invalid right-hand-side checks now raise the expected TypeError instead of silently returning false in cases where the value is not callable.
    • Existing instanceof behavior for other values remains unchanged.

…> throws TypeError

`1 instanceof Math` (and JSON/Reflect/Atomics) must throw a TypeError:
these namespace objects have no [[Call]]/[[Construct]]. The codegen
static-instanceof path mapped an unknown RHS name to class_id 0, and
`js_instanceof(_, 0)` folds to `false` — so `x instanceof Math` wrongly
returned false instead of throwing.

Add js_instanceof_noncallable_rhs() (throws the 'not callable' TypeError,
honoring the SUPPRESS_INSTANCEOF_RHS_THROW scope) and emit it from codegen
when the bare-identifier RHS is a known non-constructor built-in namespace
not shadowed by a user class. The LHS is still lowered first so its side
effects run.

Fixes S11.8.6_A6_T2. Normal `x instanceof Class/Array/Error/Object` and
the dynamic-RHS path are unchanged.

Refs #5894
@coderabbitai

coderabbitai Bot commented Jul 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Introduces a runtime helper js_instanceof_noncallable_rhs that throws a TypeError when instanceof is used with non-callable built-in namespace RHS values (Math, JSON, Reflect, Atomics), declares it as a codegen runtime symbol, and updates Expr::InstanceOf lowering to call it instead of falling through to a false result.

Changes

Non-callable instanceof RHS handling

Layer / File(s) Summary
Runtime helper for non-callable instanceof RHS
crates/perry-runtime/src/object/instanceof.rs
Adds js_instanceof_noncallable_rhs extern function returning a NaN-boxed false when suppressed, otherwise throwing a TypeError.
Codegen declaration and call-site wiring
crates/perry-codegen/src/runtime_decls/strings.rs, crates/perry-codegen/src/expr/instance_misc1.rs
Declares the new runtime symbol and adds an early guard in Expr::InstanceOf lowering to call it for unshadowed Math, JSON, Reflect, Atomics RHS values.

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

Sequence Diagram(s)

sequenceDiagram
    participant Codegen as Perry-codegen (InstanceOf lowering)
    participant Runtime as js_instanceof_noncallable_rhs
    participant JS as JS Exception Handling

    Codegen->>Codegen: Evaluate RHS identifier of instanceof
    alt RHS is Math/JSON/Reflect/Atomics and not user-defined
        Codegen->>Runtime: Call js_instanceof_noncallable_rhs()
        alt SUPPRESS_INSTANCEOF_RHS_THROW set
            Runtime-->>Codegen: Return NaN-boxed false
        else not suppressed
            Runtime->>JS: Throw TypeError
        end
    else RHS is regular class
        Codegen->>Codegen: Continue existing cid-based instanceof path
    end
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is specific, concise, and matches the PR’s main change: fixing instanceof on non-constructor namespace objects.
Description check ✅ Passed The description covers the summary, fix, related issue, and validation, but it does not fully follow the template’s exact test plan and checklist sections.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/t262-5894-instanceof-noncallable

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/perry-codegen/src/expr/instance_misc1.rs`:
- Around line 341-347: The new instanceof guard in instance_misc1 should also
catch globalThis-qualified builtins, not just bare identifiers. Update the logic
around the existing Math/JSON/Reflect/Atomics check so expressions like
globalThis.Math, globalThis.JSON, globalThis.Reflect, and globalThis.Atomics are
recognized and routed to the same js_instanceof_noncallable_rhs throw path
instead of falling through to the class-id lookup in the instanceof handling
code.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 139a81c5-212b-4a90-b736-4649d5bab2eb

📥 Commits

Reviewing files that changed from the base of the PR and between 645e5f1 and b75610d.

📒 Files selected for processing (3)
  • crates/perry-codegen/src/expr/instance_misc1.rs
  • crates/perry-codegen/src/runtime_decls/strings.rs
  • crates/perry-runtime/src/object/instanceof.rs

Comment on lines +341 to +347
if matches!(ty.as_str(), "Math" | "JSON" | "Reflect" | "Atomics")
&& !ctx.class_ids.contains_key(ty)
{
return Ok(ctx
.block()
.call(DOUBLE, "js_instanceof_noncallable_rhs", &[]));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
file='crates/perry-codegen/src/expr/instance_misc1.rs'
wc -l "$file"
sed -n '320,370p' "$file" | cat -n

Repository: PerryTS/perry

Length of output: 3205


🏁 Script executed:

#!/bin/bash
set -euo pipefail
file='crates/perry-codegen/src/expr/instance_misc1.rs'
rg -n 'globalThis\.(Math|JSON|Reflect|Atomics|EvalError|URIError|Event|CustomEvent|DOMException)|Math"|JSON"|Reflect"|Atomics"' "$file"
sed -n '370,520p' "$file" | cat -n

Repository: PerryTS/perry

Length of output: 11107


globalThis.Math/globalThis.JSON/etc. still bypass the throw path.
The new guard only matches bare identifiers, so globalThis.Math, globalThis.JSON, globalThis.Reflect, and globalThis.Atomics still fall through to the class-id lookup and can hit the js_instanceof(_, 0) -> false path instead of throwing.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/perry-codegen/src/expr/instance_misc1.rs` around lines 341 - 347, The
new instanceof guard in instance_misc1 should also catch globalThis-qualified
builtins, not just bare identifiers. Update the logic around the existing
Math/JSON/Reflect/Atomics check so expressions like globalThis.Math,
globalThis.JSON, globalThis.Reflect, and globalThis.Atomics are recognized and
routed to the same js_instanceof_noncallable_rhs throw path instead of falling
through to the class-id lookup in the instanceof handling code.

@proggeramlug
proggeramlug merged commit 143b49e into main Jul 4, 2026
17 checks passed
@proggeramlug
proggeramlug deleted the fix/t262-5894-instanceof-noncallable branch July 4, 2026 15:14
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