Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Compiler: evaluate instance var initializers at the metaclass level #6414
This currently compiles:
class Foo @x : Int32 = bar def bar 1 end end
However, it makes very little sense to run an instance var initializer at the instance level, because that's what we are initializing.
Java allows that behavior, but C# rejects it, demanding that
In any case, you can initialize it at the instance level if you want to, in an
class Foo @x : Int32 def initialize @x = bar end def bar 1 end end
That makes it much more clear that this is run at the instance level, and additionally the compiler will check that the instance var isn't used before it's assigned a value, etc.
It also makes sense from a scope level. If we do:
class Foo def bar 1 end bar # Error CONST = bar # error # but this works?: @x : Int32 = bar end
So now it's uniform:
class Foo @x : Int32 = bar # ok bar # ok CONST = bar # ok def self.bar 1 end end
This is a breaking change, but I doubt there's a lot of code out there that uses this kind of initializers.
In my opinion it seems logical that an ivar assignment behaves the same whether it is inside an
On the other hand, it's probably not that important and having a consistent rule is fine either way.
I just don't see an issue with
@Sija Even if Ruby was different... In Crystal
@asterite @straight-shoota Sorry, my bad! I already forgot that in Ruby
Actually, I tried to see if I can fix a few issues regarding initializers and instance vars... but it's all a big mess, in addition to how generics work or are implemented. I don't feel like fixing this by adding more patches and hacks. As usual, I believe it's better to have a good portion of time to rewrite the compiler from scratch, in a readable, efficient, well thought-out way (though at least I won't do that, ever, but if Crystal ever gets enough money to do it, I'd advise to do it).
I think this change make sense, at least, today.
It would be great to eventually allow the declaration-initializers lines to be evaluated in context of the instance, but only when that is made in a sound way. Rules for typing, order, dependencies of values need to be considered.
With this change, initializers of constants values (literals, loggers, etc) still work.