Skip to content

Commit

Permalink
Prevent to type ivar having initializer as nilable on assignment (#5120)
Browse files Browse the repository at this point in the history
Fixed #5112
  • Loading branch information
makenowjust authored and RX14 committed Oct 15, 2017
1 parent c1e8b70 commit 906a8cb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
18 changes: 18 additions & 0 deletions spec/compiler/semantic/initialize_spec.cr
Expand Up @@ -750,4 +750,22 @@ describe "Semantic: initialize" do
Bar.new
)) { types["Bar"] }
end

it "doesn't type ivar having initializer as nilable even if it is used before assigned inside initialize (#5112)" do
assert_type(%(
class Foo
@x = 42
def initialize
@x = x
end
def x
@x
end
end
Foo.new.x
)) { int32 }
end
end
2 changes: 1 addition & 1 deletion src/compiler/crystal/semantic/main_visitor.cr
Expand Up @@ -839,7 +839,7 @@ module Crystal

# Check if an instance variable is being assigned (for the first time)
# and self, or that same instance variable, was used (read) before that.
unless @vars.has_key?(var_name)
unless @vars.has_key?(var_name) || scope.has_instance_var_initializer?(var_name)
if (found_self = @found_self_in_initialize_call) ||
(used_ivars_node = @used_ivars_in_calls_in_initialize.try(&.[var_name]?)) ||
(@block_nest > 0)
Expand Down

0 comments on commit 906a8cb

Please sign in to comment.