Skip to content

Exclude variables' final types inside while true if re-assigned before first break#10538

Merged
straight-shoota merged 4 commits intocrystal-lang:masterfrom
HertzDevil:bug/endless-while-final-type
Mar 30, 2021
Merged

Exclude variables' final types inside while true if re-assigned before first break#10538
straight-shoota merged 4 commits intocrystal-lang:masterfrom
HertzDevil:bug/endless-while-final-type

Conversation

@HertzDevil
Copy link
Contributor

Consider the following:

while true
  x = 1    # (1)
  if ...
    break
  end
  x = ""   # (2)
end
typeof(x)  # => (Int32 | String)

typeof(x) after the exit of the while expression should not be affected by the assignment on (2), because (1) must have been executed before any break could happen. This PR makes it so that typeof(x) becomes Int32.

Note that if (1)'s RHS references x itself then the exit type would still depend on (2) as well as whatever type x has before the whole loop:

x = {1}
while true
  x = x[0]  # (1)
  if ...
    break
  end
  x = {"a"} # (2)
end

# before this PR: (Int32 | String | Tuple(String))
typeof(x) # => (Int32 | String)

This issue was discovered while trying to determine whether while exp; ...; end is always semantically equivalent to the following, provided exp isn't already the true literal:

while true
  unless exp
    break
  end
  ...
end

while loops would be a lot easier to reason about if all of them could be cast like this. This flow typing issue turned out to be a blocker whenever the while condition contains an assignment (including #10350).

@straight-shoota straight-shoota added kind:bug A bug in the code. Does not apply to documentation, specs, etc. topic:compiler:semantic labels Mar 23, 2021
Copy link
Member

@asterite asterite left a comment

Choose a reason for hiding this comment

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

Thank you! ❤️

@straight-shoota straight-shoota added this to the 1.1.0 milestone Mar 26, 2021
@straight-shoota straight-shoota merged commit fb8bbed into crystal-lang:master Mar 30, 2021
@HertzDevil HertzDevil deleted the bug/endless-while-final-type branch March 30, 2021 09:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind:bug A bug in the code. Does not apply to documentation, specs, etc. topic:compiler:semantic

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants