Skip to content

Unhelpful formatting of commented binary operator expressions #13736

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
azizk opened this issue Jul 24, 2024 · 3 comments
Closed

Unhelpful formatting of commented binary operator expressions #13736

azizk opened this issue Jul 24, 2024 · 3 comments

Comments

@azizk
Copy link
Contributor

azizk commented Jul 24, 2024

Elixir and Erlang/OTP versions

Erlang/OTP 27 [erts-15.0] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]

Elixir 1.17.2 (compiled with Erlang/OTP 27)

Operating system

NixOS

Current behavior

When formatting code that involves multiline binary operator expressions and comments in-between, the Elixir formatter produces an unhelpful result. The following:

# Comment about expression 1
expression1 ||
  # Comment about expression 2
  expression2 ||
  # Comment about expression 3
  expression3

formats as:

# Comment about expression 1
# Comment about expression 2
# Comment about expression 3
expression1 ||
  expression2 ||
  expression3

Expected behavior

I would expect the formatter to allow placing comments between the lines, so that we can comment the specific expressions properly:

# Comment about expression 1
expression1 ||
  # Comment about expression 2
  expression2 ||
  # Comment about expression 3
  expression3
@josevalim
Copy link
Member

Correct, the formatter cannot preserve code comments in all situations. Some of them were already documented but this particular one was not. I have pushed updates to the documentation.

Unfortunately tackling this is non-trivial. If someone wants to give it a try, pull requests are welcome, but it is not something we intend to pursue ourselves. Thanks!

@josevalim josevalim closed this as not planned Won't fix, can't repro, duplicate, stale Jul 24, 2024
@azizk
Copy link
Contributor Author

azizk commented Jul 24, 2024

Okay, thanks for the explanation and update to the docs. 👍

If someone is curious how to work around this, you'd basically have to break up the expressions and use a result variable:

# Comment about expression 1
result = expression1
# Comment about expression 2
result = result || expression2
# Comment about expression 3
result = result || expression3

@josevalim
Copy link
Member

You can also break the expressions into private functions, if they are complex enough to warrant for comments. With the advantage that the function names can also provide meaningful context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants