Skip to content

fix(ts-optimizer): keep outer loop items in scope for nested loop handlers - #9231

Merged
Varixo merged 3 commits into
QwikDev:mainfrom
SahinurDEV:fix/ts-optimizer-nested-loop-captures
Oct 22, 2026
Merged

Varixo merged 3 commits into
QwikDev:mainfrom
SahinurDEV:fix/ts-optimizer-nested-loop-captures

Conversation

@SahinurDEV

@SahinurDEV SahinurDEV commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What is it?

  • Bug

Description

Fixes #9190.

What was wrong. A handler inside a nested loop that captures the outer loop's item crashes SSR:

{props.facets.map((facet) => (
  <div key={facet.slug}>
    {facet.items.map((item) => (
      <input onChange$={() => props.toggle$(facet.slug, item.slug)} />
    ))}
  </div>
))}

The TypeScript optimizer emitted the handler's .w([facet, props]) binding at the top of the component body, outside both loops, so the server build threw ReferenceError: facet is not defined. In hoist builds it also renamed the loop param to facet1, because a free facet now existed at component scope.

Root cause. Loop handlers whose remaining captures need a .w() binding go through two placement paths, and neither looked past the component body:

  • Hoist / SSR (rewrite/inline-body.ts). Every binding was inserted before the component's top-level statement that uses it. That's correct only when all captures are declared in the component body. The regression came from 42323eb.
  • Segment builds (segment/body-transforms.ts).
    • The scope scan only checked hoistedCaptureNames[0].
    • It matched arrow params by splitting the param text on ,, so a typed param like (facet: Facet) never matched.
    • It didn't recognise for…of heads.
    • Untyped .map((facet) => …) worked by luck. The issue's TSX code didn't.

Fix. I followed the Rust optimizer, which hoists the binding to the deepest scope among its captures' declarations and turns an expression-bodied callback into a block body to make room for it.

  • inline-body.ts.
    • Parses the body (as before) and walks from the use site outward.
    • Finds the innermost function, loop or block that declares one of the captures, and inserts the binding before the statement that uses it.
    • If that scope is an expression-bodied arrow, it becomes { const s_X = q_X.w([…]); return …; }. The original parens are kept and return stays on the same line.
    • When every capture is component-scoped, the result is the same as before.
  • body-transforms.ts.
    • Takes the innermost scope over all captures.
    • Parses the arrow param list (so typed, defaulted and destructured params resolve).
    • Recognises for (const x of …) { heads.

Generated SSR output for the snippet above now looks like this:

props.facets.map((facet) => {
    const s_pQ1qdbZ4Qs4 = q_qrl_4294901760.w([facet, props]);
    return _jsxSorted("div", null, null, facet.items.map((item) => _jsxSorted("label", …, { "q-e:change": s_pQ1qdbZ4Qs4, "q:p": item } …

How it was tested.

  • New packages/ts-optimizer/tests/optimizer/jsx/nested-loop-capture-scope.test.ts covers:
    • SSR hoist with the plugin's strip options
    • hoist without stripping
    • client smart segments with typed params
    • a block-bodied outer callback with a local const
    • nested for…of loops
    • the single-loop case staying at component scope
    • 5 of these fail without the fix; all 6 pass with it.
  • New runtime spec in packages/qwik/src/core/tests/loops.spec.tsx (nested expression-bodied loops, outer item and props captured).
    • Without the fix, against a rebuilt dist/ts-optimizer.mjs: ssrRenderToDom fails with ReferenceError: facet is not defined and domRender logs nothing.
    • With the fix, both pass.
  • packages/ts-optimizer: vitest run gives 1543 passed / 1 skipped, including the convergence and rust-behavior-parity suites. tsc --noEmit is clean.
  • vitest run packages/qwik/src (after pnpm build --qwik --optimizer --dev): 2649 passed / 18 skipped.
  • eslint and prettier --check on the changed files: clean.

Checklist

  • My code follows the developer guidelines of this project
  • I performed a self-review of my own code
  • I added a changeset with pnpm change
  • I added new tests to cover the fix / functionality

Summary by CodeRabbit

  • Bug Fixes
    • Fixed event handlers in nested loops so each interaction uses the correct outer and inner items. Clicking an item in one group no longer risks using values from another group, keeping displayed results and actions consistent with the selected item.

…dlers

A handler inside an inner `.map()` that captured the outer loop's item got
its `.w([...])` binding hoisted to the component body, where the outer item
does not exist, so SSR threw `ReferenceError: facet is not defined`.

Place the binding in the innermost scope that declares one of its captures,
converting an expression-bodied outer callback into a block body, as the
Rust optimizer does. The segment path also resolves typed loop params and
`for...of` heads now, and looks at every capture instead of the first.

Fixes #9190
@SahinurDEV
SahinurDEV requested a review from a team as a code owner October 19, 2026 04:46
@changeset-bot

changeset-bot Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 983a74b

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 8 packages
Name Type
@qwik.dev/core Patch
@qwik.dev/devtools Patch
eslint-plugin-qwik Patch
@qwik.dev/mcp Patch
@qwik.dev/react Patch
@qwik.dev/router Patch
@qwik.dev/utils Patch
create-qwik Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@Varixo

Varixo commented Oct 20, 2026

Copy link
Copy Markdown
Member

Hey, thanks for the PR! Added some comments. Also worth adding snapshots for rust -> ts optimizer compability

… nested loop bindings

Wrap expression-bodied callbacks at the parsed body start so comments after => no longer drop the JSX or break the build, and group hoisted .w() bindings per enclosing scope so sibling nested loops don't share one callback. Adds regression tests for both cases.
@coderabbitai

coderabbitai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6f686530-5c22-4b5b-9146-2b7c9db35c0c
📥 Commits

Reviewing files that changed from the base of the PR and between f066d87 and 983a74b.

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:

  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 180c1f46-1a4c-4bd6-b457-deccbacc723e
📥 Commits

Reviewing files that changed from the base of the PR and between f33a2bc and f066d87.

📒 Files selected for processing: 5
  • .changeset/ts-optimizer-nested-loop-captures.md
  • packages/qwik/src/core/tests/loops.spec.tsx
  • packages/ts-optimizer/src/optimizer/rewrite/inline-body.ts
  • packages/ts-optimizer/src/optimizer/segment/body-transforms.ts
  • packages/ts-optimizer/tests/optimizer/jsx/nested-loop-capture-scope.test.ts

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

📝 Walkthrough

The TypeScript optimizer now places loop-handler declarations in scopes that contain their captured values. Regression tests cover nested map() and for...of loops, and a Changeset declares a patch release for @qwik.dev/core.

Changes: Nested Loop Captures

Layer / File(s) Summary
Capture-scope detection
packages/ts-optimizer/src/optimizer/segment/body-transforms.ts
Capture detection recognizes bindings in loop heads and parsed arrow parameters. Hoisted declarations are positioned and grouped by scope.
Scope-aware declaration insertion
packages/ts-optimizer/src/optimizer/rewrite/inline-body.ts
Loop-handler declarations retain capture names and are inserted before use in the innermost scope that declares a capture. The transform also handles single-statement loop bodies and expression-bodied callbacks.
Regression coverage and release note
packages/ts-optimizer/tests/optimizer/jsx/nested-loop-capture-scope.test.ts, packages/qwik/src/core/tests/loops.spec.tsx, .changeset/ts-optimizer-nested-loop-captures.md
Tests cover nested and sibling loops, single-loop captures, commented callbacks, and handler behavior. The Changeset declares a patch release.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: varixo

Merge Risk: ⚪ Minimal · up to f066d

No actionable issue remains in the reviewed change. It is ready to merge after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 64.71% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 4 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: keeping outer loop items in scope for nested loop handlers in the TypeScript optimizer.
Linked Issues check Passed Issue #9190 requires nested-loop handler captures to remain in scope during production rendering. The change places .w() bindings in the innermost scope that declares each capture, resolves typed ar…
Out of Scope Changes check Passed The changes stay within issue #9190. The optimizer changes implement capture-scope placement. The new optimizer and runtime tests verify the production failure and the supported loop forms. The change…
Full details: Linked Issues check

Explanation

Issue #9190 requires nested-loop handler captures to remain in scope during production rendering. The change places .w() bindings in the innermost scope that declares each capture, resolves typed arrow parameters, and recognizes for...of bindings. The regression tests cover SSR hoist output, client segments, nested loops, sibling loops, and the single-loop case. The runtime test covers SSR and DOM rendering.

Full details: Out of Scope Changes check

Explanation

The changes stay within issue #9190. The optimizer changes implement capture-scope placement. The new optimizer and runtime tests verify the production failure and the supported loop forms. The changeset records the related patch release. No unrelated behavior or files are demonstrated.

Full details: Docstring Coverage

Explanation

Docstring coverage is 64.71% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 4 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@SahinurDEV

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @Varixo! Both issues are addressed in f066d87:

  • Comment after =>: I removed the lastIndexOf('=>') text scan and now use the parsed arrow body's start position, so a comment after => no longer drops the JSX (and /* => */ no longer breaks the hoist build).
  • Sibling nested loops: hoisted bindings now record their enclosing lexical scope and are grouped only within that scope, which fixes the ReferenceError.

I added regression tests for all three cases in nested-loop-capture-scope.test.ts, covering both the server and client builds. They fail on the previous code and pass now. The full ts-optimizer suite and typecheck pass locally. Could you take another look?

@pkg-pr-new

pkg-pr-new Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@qwik.dev/core

npm i https://pkg.pr.new/QwikDev/qwik/@qwik.dev/core@9231

@qwik.dev/router

npm i https://pkg.pr.new/QwikDev/qwik/@qwik.dev/router@9231

@qwik.dev/utils

npm i https://pkg.pr.new/QwikDev/qwik/@qwik.dev/utils@9231

eslint-plugin-qwik

npm i https://pkg.pr.new/QwikDev/qwik/eslint-plugin-qwik@9231

create-qwik

npm i https://pkg.pr.new/QwikDev/qwik/create-qwik@9231

@qwik.dev/optimizer

npm i https://pkg.pr.new/QwikDev/qwik/@qwik.dev/optimizer@9231

@qwik.dev/devtools

npm i https://pkg.pr.new/QwikDev/qwik/@qwik.dev/devtools@9231

@qwik.dev/mcp

npm i https://pkg.pr.new/QwikDev/qwik/@qwik.dev/mcp@9231

commit: 983a74b

@Varixo Varixo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for this, lgtm

@Varixo
Varixo merged commit 78ba610 into QwikDev:main Oct 22, 2026
tuurbo added a commit to tuurbo/qwik that referenced this pull request Oct 26, 2026
A loop event handler's `.w([...])` binding must be declared where all of
its captures are in scope. Both optimizers missed that in some shapes:

- Rust treated every hoisting function as having a body-block scope, so in
  a component that returns its JSX directly the outer loop item matched the
  component and the binding was hoisted out of both loops (SSR
  ReferenceError). It also resolved captures by name to their outermost
  declaration, so a handler in `function f(results)` captured a shadowed
  component `results`.
- The TS optimizer dropped these bindings in hoist builds of such
  components, and segment builds found scopes by scanning source text,
  which missed loop callbacks without parentheses and `function` scopes.
  Segment builds now share the hoist path's parsed-scope placement.

Fixes QwikDev#9306
Refs QwikDev#9190, QwikDev#9231

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tuurbo added a commit to tuurbo/qwik that referenced this pull request Oct 26, 2026
A loop event handler's `.w([...])` binding must be declared where all of
its captures are in scope. Both optimizers missed that in some shapes:

- Rust treated every hoisting function as having a body-block scope, so in
  a component that returns its JSX directly the outer loop item matched the
  component and the binding was hoisted out of both loops (SSR
  ReferenceError). It also resolved captures by name to their outermost
  declaration, so a handler in `function f(results)` captured a shadowed
  component `results`.
- The TS optimizer dropped these bindings in hoist builds of such
  components, and segment builds found scopes by scanning source text,
  which missed loop callbacks without parentheses and `function` scopes.
  Segment builds now share the hoist path's parsed-scope placement, which
  throws instead of dropping a binding it cannot place.

Fixes QwikDev#9306
Refs QwikDev#9190, QwikDev#9231

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tuurbo added a commit to tuurbo/qwik that referenced this pull request Oct 27, 2026
A loop event handler's `.w([...])` binding must be declared where all of
its captures are in scope. Both optimizers missed that in some shapes:

- Rust treated every hoisting function as having a body-block scope, so in
  a component that returns its JSX directly the outer loop item matched the
  component and the binding was hoisted out of both loops (SSR
  ReferenceError). It also resolved captures by name to their outermost
  declaration, so a handler in `function f(results)` captured a shadowed
  component `results`.
- The TS optimizer dropped these bindings in hoist builds of such
  components, and segment builds found scopes by scanning source text,
  which missed loop callbacks without parentheses and `function` scopes.
  Segment builds now share the hoist path's parsed-scope placement, which
  throws instead of dropping a binding it cannot place.

Fixes QwikDev#9306
Refs QwikDev#9190, QwikDev#9231

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tuurbo added a commit to tuurbo/qwik that referenced this pull request Oct 28, 2026
A loop event handler's `.w([...])` binding must be declared where all of
its captures are in scope, before its first use. Both optimizers missed
that in some shapes:

- Rust treated every hoisting function as having a body-block scope, so in
  a component that returns its JSX directly the outer loop item matched the
  component and the binding was hoisted out of both loops (SSR
  ReferenceError). It also resolved captures by name to their outermost
  declaration, so a handler in `function f(results)` captured a shadowed
  component `results`.
- The TS optimizer dropped these bindings in hoist builds of such
  components, and segment builds found scopes by scanning source text,
  which missed loop callbacks without parentheses and `function` scopes.
  Segment builds now share the hoist path's parsed-scope placement, which
  throws instead of dropping a binding it cannot place.
- Both declared the binding after the last `const`/`let` in its scope, so
  it read a local before a later reassignment, and JSX built into a
  `const` used it before its declaration (ReferenceError). It now goes
  right before the first statement that uses it; calls to a hoisted
  function declaration, or JSX tags rendering it, count as uses.

Fixes QwikDev#9306
Refs QwikDev#9190, QwikDev#9231

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tuurbo added a commit to tuurbo/qwik that referenced this pull request Oct 28, 2026
A loop event handler's `.w([...])` binding must be declared where all of
its captures are in scope, before its first use. Both optimizers missed
that in some shapes:

- Rust treated every hoisting function as having a body-block scope, so in
  a component that returns its JSX directly the outer loop item matched the
  component and the binding was hoisted out of both loops (SSR
  ReferenceError). It also resolved captures by name to their outermost
  declaration, so a handler in `function f(results)` captured a shadowed
  component `results`.
- The TS optimizer dropped these bindings in hoist builds of such
  components, and segment builds found scopes by scanning source text,
  which missed loop callbacks without parentheses and `function` scopes.
  Segment builds now share the hoist path's parsed-scope placement, which
  throws instead of dropping a binding it cannot place.
- Both declared the binding after the last `const`/`let` in its scope, so
  it read a local before a later reassignment, and JSX built into a
  `const` used it before its declaration (ReferenceError). It now goes
  right before the first statement that uses it; calls to a hoisted
  function declaration, or JSX tags rendering it, count as uses. TS also
  keeps it below its captures' declarations; Rust never captures a local
  declared later.

Fixes QwikDev#9306
Refs QwikDev#9190, QwikDev#9231

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

[🐞] Production build hoists a nested .map() handler's captures out of both loops, so SSR fails

2 participants