Crystal: `a : Bool` can be read before assignement

Created on 10 Feb 2018  Â·  6Comments  Â·  Source: crystal-lang/crystal

b = a : Bool

pp a # Error: read before assignment to local variable 'a'
pp b # => nil

This sounds like a bug, the first line should give the read before assignement error.

bug compiler topicparser

Most helpful comment

I think it should just be a syntax error

All 6 comments

A variable declaration has Nil as a type

So this is expected behavior for you @asterite ?

And why does a variable declaration have a type?

Because everything has a type.

I think there is a similar or same issue already for this, I think this is a duplicate.

Here's a similar issue: https://github.com/crystal-lang/crystal/issues/3641

I don't have a strong opinion on either because I can't find a use case for doing that, but we can brainstorm about it.

I think it should just be a syntax error

It's nice to allow variable declaration as an expression, which then, imo, absolutely must have the type — and return the value — after it's declaration. In which case that definitely would be a syntax error,
Anything else is outlandishly unintuitive. The declaration should be hoisted to before the expression it is used in, in the AST-transformations.

Compare:

x = 47

# Let's do some stuff
if a1 = x
    p "Using a1, #{a1}" 
else 
    p "Not using a1, #{a1}" 
end

# "Hey! I'm gonna make it a tad better typed, let's add the obvious type of a!
# ...What could possibly go wrong?"
if a2 : Int32 = x
    p "Using a2, #{a2}" 
else 
    p "Not using a2, #{a2}" 
end

Output:

"Using a1, 47"
"Not using a2, 47"

So b = a : Bool = true should be legal. But looks kind of weird. The alternative would be to make it a pure statement.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

oprypin picture oprypin  Â·  3Comments

lgphp picture lgphp  Â·  3Comments

jhass picture jhass  Â·  3Comments

asterite picture asterite  Â·  3Comments

ArthurZ picture ArthurZ  Â·  3Comments