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

Instance var is incorrectly considered nil when class var initializer is involved #3988

Closed
bcardiff opened this issue Feb 2, 2017 · 1 comment
Labels
kind:bug A bug in the code. Does not apply to documentation, specs, etc. topic:compiler
Milestone

Comments

@bcardiff
Copy link
Member

bcardiff commented Feb 2, 2017

Given the following code for Bar

class Bar
  @baz = 0

  def initialize
    begin
      @baz = 42
    rescue
    end
  end
end

The following code won't compile:

class Foo
  @@bar = Bar.new
end
Error in foo.cr:13: instantiating 'Bar:Class#new()'

  @@bar = Bar.new
              ^~~

instance variable '@baz' of Bar must be Int32, not Nil

Error: instance variable '@baz' is initialized inside a begin-rescue, so it can potentially be left uninitialized if an exception is raised and rescued

Note that however the code

class Foo
  @bar = Bar.new
end

pp Foo.new # => #<Foo:0x10b1c9f00 @bar=#<Bar:0x10b1cefd0 @baz=42>>

does works as expected.

Might be related to #3706 , extracted from crystal-lang/crystal-mysql#22

$ crystal --version
Crystal 0.20.5 (2017-01-20)
@bcardiff bcardiff added kind:bug A bug in the code. Does not apply to documentation, specs, etc. topic:compiler labels Feb 3, 2017
bcardiff pushed a commit that referenced this issue Feb 22, 2017
@bcardiff
Copy link
Member Author

reduced to the following code.

class Foo
  @@foo = Foo.new

  @never_nil = 0

  def initialize
    if false
      @never_nil = 0
    end
  end
end
$ crystal build foo.cr 
Error in foo.cr:2: instance variable '@never_nil' of Foo must be Int32, not Nil

  @@foo = Foo.new

$ crystal --version
Crystal 0.21.0 (2017-02-21)

@asterite asterite mentioned this issue Feb 23, 2017
@asterite asterite changed the title Rescue in initialize can lead to uninitialized instance variables (take 2) Instance var is incorrectly considered nil when class var initializer is involved Feb 23, 2017
@asterite asterite added this to the Next milestone Mar 4, 2017
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
Projects
None yet
Development

No branches or pull requests

2 participants