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

Fix: rebind while condition variables after while body #6295

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions spec/compiler/semantic/while_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -169,4 +169,32 @@ describe "Semantic: while" do
a
)) { nilable int32 }
end

it "rebinds condition variable after while body (#6158)" do
assert_type(%(
class Foo
@parent : self?
def parent
@parent
end
end
class Bar
def initialize(@parent : Foo)
end
def parent
@parent
end
end
a = Foo.new
b = Bar.new(a)
while b = b.parent
break if 1 == 1
end
b
)) { nilable types["Foo"] }
end
end
16 changes: 16 additions & 0 deletions src/compiler/crystal/semantic/main_visitor.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2081,6 +2081,22 @@ module Crystal
node.body.accept self
end

# After while's body, bind variables *before* the condition to the
# ones after the body, because the loop will repeat.
#
# For example:
#
# x = exp
# # x starts with the type of exp
# while x = x.method
# # but after the loop, the x above (in x.method)
# # should now also get the type of x.method, recursively
# end
before_cond_vars.each do |name, before_cond_var|
var = @vars[name]?
before_cond_var.bind_to(var) if var && !var.same?(before_cond_var)
end

cond = node.cond.single_expression

endless_while = cond.true_literal?
Expand Down