eclipse-archived / ceylon.formatter

A formatter for the Ceylon programming language, written in Ceylon.
Apache License 2.0
14 stars 11 forks source link

if/else each on one line not supported #130

Closed lucaswerkmeister closed 7 years ago

lucaswerkmeister commented 7 years ago
if (true) { print(1); }
else { print(2); }

The formatter turns this into

if (true) { print(1); } else { print(2); }

because an else normally goes on the same line as the preceding }, under the assumption that this } is already on its own line. Single-line ifs violate that assumption.

Which solution would be preferred here?

Thoughts?

lucaswerkmeister commented 7 years ago

If we decide to not allow single-line ifs with an else (first solution), then the implementation would probably be a Category of Blocks that are not allowed to be single-line (FormattingVisitor member), which visitIf adds blocks to and visitBlock consults. And in that case, I think I’d also like to add method blocks (and, if necessary, class/interface bodies) to that category as well.

quintesse commented 7 years ago

Personally I'm a proponent of the first solution. I never write single line ifs in Java for example, I always use blocks even for the tiniest of statements, I find the visual regularity more readable myself and prefer it over making the code shorter. But I admit it's completely personal, I can perfectly understand people seeing things differently.

lucaswerkmeister commented 7 years ago

Well, those people still have to live with the fact that we didn’t make braces optional in Ceylon ;)

I think I prefer the first solution as well. I wrote the original code in the issue, but still, it looks weird to me now.

gavinking commented 7 years ago

@lucaswerkmeister I think whatever you do, it should be consistent with how you handle switch statements and try statements with catch clauses.

lucaswerkmeister commented 7 years ago

Well, currently, this is allowed:

try { print("hi"); } catch (Exception e) { e.printStackTrace(); } finally { print("done"); }

So I’d say those are some more candidates for blocks that aren’t allowed to have a single-line form.

It might actually make more sense to turn this around and say that only these kinds of blocks are allowed to be single-line (if they contain at most one statement):

Anything else? I looked for Block in the spec, and these are the only productions where single-line blocks make sense IMO. (Some constructs, like functions and getters, should instead use => in these cases; others should never be single-line IMO.)