The Crystal Programming Language Forum

`if <conditional> true else <falsy> end` throwing error

Hello, I am learning Crystal and am exploring the syntax. Few days ago I wanted to try the expression: if x == 10 true else false end, that seemed to throw an error: Error: unexpected token: true. However, the multiline version of this works, and in single line version, any other value than a Bool works (i.e. if x == 10 :true else false end works). Is there any particular reason why a Bool wouldn’t work in a one liner conditional?

Thank you.

It’s a bug. I think none should compile, you need a semicolon in every case.


Currently, after a condition is parsed, the parser basically just continues parsing the next expression (which is then part of the condition’s branch). There is no explicit requirement for an expression separator (newline or semi-colon). The only restriction (by parse_op_assign(allow_suffix: false)) is that the first token after the expression cannot be an identifier. Hence true does not work, but :true does (true is lexed as an identifier).

This applies to all conditional clauses, not just if.

I think it would be reasonable to require an expression separator after the condition. This is mandatory in Ruby, too.