Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

for-of loop variable scoping is invalid for nested loops #8010

Closed
simplan-niklas opened this issue Sep 26, 2023 · 1 comment · Fixed by #9151
Closed

for-of loop variable scoping is invalid for nested loops #8010

simplan-niklas opened this issue Sep 26, 2023 · 1 comment · Fixed by #9151
Labels
Milestone

Comments

@simplan-niklas
Copy link

Describe the bug

If another loop (such as a basic for-loop or while-loop) is nested inside a for-of loop, the compiler doesn't recognize that the closure inside the inner loop closes over the outer loop variable.

Input code

for (const x of [0, 1, 2]) {
    for (let i = 0; i < 1; i++) {
        setTimeout(() => console.log(x));
    }
}

Config

{
  "jsc": {
    "parser": {
      "syntax": "ecmascript",
      "jsx": false
    },
    "target": "es5",
    "loose": false,
    "minify": {
      "compress": false,
      "mangle": false
    }
  },
  "module": {
    "type": "es6"
  },
  "minify": false,
  "isModule": true
}

Playground link

https://play.swc.rs/?version=1.3.89&code=H4sIAAAAAAAAAzWMTQqAIBQG957iWypGaNt%2BTtEuWoWGYD2oFwTh3dOg2cxmGE8H5EL7ybhBHpOpYCs0s8IjkPEliI4R0MO0WR1sltZ%2FUTgdj2FzdLGUCv2AsqTo6kirvJVqvzKJJF4nGb25cQAAAA%3D%3D&config=H4sIAAAAAAAAA1WPSw7DIAwF9zkF8rrbdtE79BAWdSIifrKJVBTl7iUE0maH3xsz8jooBbNoeKq1PMsQkYX4nEsi2Sf8lARIOxTNJia49XaWvRrRCtVoOxpIyBOluiX3hoMNQajjLXPGmzH%2FC3VwkUnkCu4o%2BsnSVTc0JbjwXmrZDkk50qF%2FwA%2FqsvNjMPLqm4kXGrYvhlQioBQBAAA%3D

SWC Info output

No response

Expected behavior

The code should print

0
1
2

Actual behavior

The code prints

2
2
2

Version

1.89

Additional context

No response

@kdy1 kdy1 added this to the Planned milestone Sep 26, 2023
@kdy1 kdy1 closed this as completed in #9151 Jul 8, 2024
kdy1 pushed a commit that referenced this issue Jul 8, 2024
**Description:**

The original code separately records the usage of variables and checks if there is a closure. Changed to only record variables used in a closure.

**Related issue:**

 - Closes #8010
@kdy1 kdy1 modified the milestones: Planned, v1.7.0 Jul 17, 2024
@swc-bot
Copy link
Collaborator

swc-bot commented Aug 17, 2024

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@swc-project swc-project locked as resolved and limited conversation to collaborators Aug 17, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Development

Successfully merging a pull request may close this issue.

3 participants