Skip to content

Commit 906a8cb

Browse files
makenowjustRX14
authored andcommitted
Prevent to type ivar having initializer as nilable on assignment (#5120)
Fixed #5112
1 parent c1e8b70 commit 906a8cb

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

spec/compiler/semantic/initialize_spec.cr

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -750,4 +750,22 @@ describe "Semantic: initialize" do
750750
Bar.new
751751
)) { types["Bar"] }
752752
end
753+
754+
it "doesn't type ivar having initializer as nilable even if it is used before assigned inside initialize (#5112)" do
755+
assert_type(%(
756+
class Foo
757+
@x = 42
758+
759+
def initialize
760+
@x = x
761+
end
762+
763+
def x
764+
@x
765+
end
766+
end
767+
768+
Foo.new.x
769+
)) { int32 }
770+
end
753771
end

src/compiler/crystal/semantic/main_visitor.cr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -839,7 +839,7 @@ module Crystal
839839

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

0 commit comments

Comments
 (0)