Crystal: Syntax error with `&&`, `||` on separate line

Created on 10 Nov 2017  路  4Comments  路  Source: crystal-lang/crystal

Issue:

Crystal has a syntax error when an && statement is on another line - it's the same with ||. It seems as if the parser parses the && false as one separate instruction as opposed to part of val. I'm not sure whether this is a valid issue or not, but it's best to get everyone's thoughts.

Minified example:

val = true
  && false

puts val

Most helpful comment

Closing. Line feeds are significant and terminate an expression. The operator must appear on the previous line so the linefeed becomes insignificant.

All 4 comments

Use:

val = true &&
  false

As to why it is a syntax error, this is because val = true is a valid expression, and && false on a new line is taken as a new expression, which is not valid.
Using && at the end of the line makes val = true && an expression that is not terminated, and the end of that expression is looked on the next line so this works.

This is a consequence of the language not requiring a semi-colon at the end of every statement. You'll get the same result in almost any language that works this way (Python, Ruby, Elixir, etc.).

When the parser requires a semi-colon to end the statement, it can freely skip newlines and interpret your example as you would expect. But, as bew said, without the semi-colon, the newline is important in indicating the end of the statement.

Closing. Line feeds are significant and terminate an expression. The operator must appear on the previous line so the linefeed becomes insignificant.

FWIW, if you feel you really want to have the && start on a new line, then you can escape the newline on the previous line using the \ character. Eg:

val = true \
  && false

puts val

Note that the \ must be the final character before the newline which ends that line. There must not be any spaces or tabs after the \. Usually it makes much more sense to just move the operator you're using (&&, ||, +, etc) up to the previous line, as everyone has described.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cjgajard picture cjgajard  路  3Comments

asterite picture asterite  路  3Comments

RX14 picture RX14  路  3Comments

pbrusco picture pbrusco  路  3Comments

Sija picture Sija  路  3Comments