Bugfix: How to handle @for loop variable scoping in Ivy codegen's co...
Documentation for Sessions
🐛 Bugfix: How to handle @for loop variable scoping in Ivy codegen's co...
Date: 2026-03-24
Time: 19:46:50 UTC
Session: gspace1-264.8
Agent: backend
Confidence: 95%
Status: ✅ Documented
📋 Decision Context
Question:
How to handle @for loop variable scoping in Ivy codegen's contextualizeExpr?
Task: S264.5: Fix @for loop variable scoping in Ivy codegen
🎯 Decision Made
Chosen:
Instance-level currentLocalVars scope tracking with save/restore on @for entry/exit, plus operator-aware local var check
Options Considered:
- Option A: Pass localVars as parameter to every contextualizeExpr call (too invasive, 15+ call sites)
- Option B: Instance field currentLocalVars with save/restore (chosen — minimal changes, correct scoping)
- Option C: Use CodegenContext to carry local vars (breaks separation — codegen shouldn't depend on context for expression logic)
💭 Reasoning
Root cause: contextualizeExpr prepended ctx. to ALL identifiers. Inside @for(item of items()), item.name became ctx.item.name. Three sub-problems: (1) simple local var access (item.name) — solved by checking root identifier against currentLocalVars; (2) compound expressions (item.id === selectedId()) — the naive check returned the WHOLE expression because the first identifier was local. Fixed by only applying local var early-return for expressions WITHOUT comparison/logical operators. When operators present, the expression is split and each part contextualized independently; (3) track expression (track item.id) double-prefixed because old code did ctx. then replace. Fixed by contextualizing with item already in scope. The scope is stack-based: saved before entering @for, restored after. This handles nested @for blocks correctly.
📁 Files Involved
libs/libs-structural/platform-preview/src/lib/compiler/ivy-codegen.ts
🔗 Related
- Decision ID:
dev_1774381610512_sib5w8j - Session: 264
- Workspace: gspace1
Auto-generated by MCP Smart Consolidation