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

Ruby: Improve desugaring of for loops #13937

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

hvitved
Copy link
Contributor

@hvitved hvitved commented Aug 10, 2023

Previously, we would desugar for loops

for x in xs do
  # body
end

into

xs.each do |synth|
  x = synth
  # body
end

However, when the iteration variable x is used after the loop (as a captured variable inside the loop), the rewrite only becomes correct when x either has a prior assignment, or if we add a nil initialization.

This PR therefor improves the desugaring by adding a conditional initial assignment:

if not defined?(x) then
  x = nil
end

xs.each do |synth|
  x = synth
  # body
end

The rewrite also works when there are multiple iteration variables:

for x, y in xs do
  # body
end

gets desugared into

if not defined?(x) then
  x = nil
end

if not defined?(y) then
  y = nil
end

xs.each do |synth|
  x, y = synth
  # body
end

@hvitved hvitved added the no-change-note-required This PR does not need a change note label Aug 10, 2023
@hvitved hvitved marked this pull request as ready for review August 10, 2023 12:55
@hvitved hvitved requested a review from a team as a code owner August 10, 2023 12:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-change-note-required This PR does not need a change note Ruby
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant