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

Compiler should be smarter about immutable closured variables #3093

Closed
asterite opened this issue Aug 4, 2016 · 1 comment · Fixed by #9986
Closed

Compiler should be smarter about immutable closured variables #3093

asterite opened this issue Aug 4, 2016 · 1 comment · Fixed by #9986

Comments

@asterite
Copy link
Member

asterite commented Aug 4, 2016

I couldn't find a way to reduce the title's size, but basically:

def capture(&block)
  block
end

x = rand < 0.5 ? 1 : nil
if x
  capture do
    x + 1 # undefined method '+' for Nil (compile-time type is (Int32 | Nil))
  end
end

Even though we check that x is not nil, and it's never modified again, the compiler complains because right now any closured variable has all types all the time (they are not affected by type flow). This should be improved by noticing that x doesn't change. It's not trivial because if inside a while or another block it gets tricky, but should be doable.

@asterite
Copy link
Member Author

This should also work:

x = 1
x = "hello"

capture do
  x # here x is known to always be a String, never an Int32
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants