if 1 < 0
local_var = true
raise "foo"
end
local_var # => nil
In the last line, local_var can't actually be defined because it's only defined in a branch that raises. The assignment in line 2 could never have happened before the variable is accessed in line 6.
Outside the if branch, it should be treated like it was never assigned in the first place:
if 1 < 0
raise "foo"
end
local_var # Error: undefined local variable or method 'local_var' for top-level
It's probably not a super important feature, but it would be useful if the compiler could detect that.
This has surfaced in #9376: After extracting a noreturn branch to a separate method, the compiler complained about an undefined local variable when it wasn't defined for the main branch in the first place.
I guess this is because local variables are a parser level feature, while branch analysis only happens in semantic.
Yes, I was going to reply what jhass said.
I thought all local-var definitions are method-scoped, the type was just nil if it was impossible to be assigned in that branch of the code.
should this issue be closed?
Why? I think this is a valid feature enhancement. It's not going to be implemented anytime soon. But it does not seem to be impossible.
It's a really really wide-ranging language change if we change the scoping rules for local variables... I don't see this happening but maybe others want to weigh in.
Outside the if branch, it should be treated like it was never assigned in the first place
That's the current behavior: not assigned means nil.
I don't think there's anything to do here.
Maybe this is something a linter like ameba could help with.
@straight-shoota IIRC it already does that :)
Most helpful comment
It's a really really wide-ranging language change if we change the scoping rules for local variables... I don't see this happening but maybe others want to weigh in.