dlang-community / dfmt

Dfmt is a formatter for D source code
Boost Software License 1.0
204 stars 47 forks source link

Align declaration comments #227

Open MartinNowak opened 8 years ago

MartinNowak commented 8 years ago

Not the biggest fan of that myself but apparently aligning comments is one of the remaining issues blocking dfmt adoption for dmd (see https://github.com/D-Programming-Language/dmd/pull/5217 and https://github.com/D-Programming-Language/dmd/pull/5354). The main use case is something like this https://github.com/D-Programming-Language/dmd/blob/6cd71735f346b1fedb4b2740592773bc0849e2e0/src/globals.d#L61-L87, a list of declarations each followed by a comment.

Hackerpilot commented 8 years ago

I've been putting this off because of how hard it is to get right. Here's a simple example of code that will cause a straightforward algorithm to fail:

int a;                                             /// comment for a
int*b = someInitializationFuntion(a,b,c,d,e+f);    /// comment for b

To correctly format the first line the algorithm must know ahead of time that extra spacing will be added to the second line. (It is missing spaces around commas and operators). An algorithm can't look just one line ahead, either. It must look an arbitrary number of lines ahead.

MartinNowak commented 8 years ago

Yep, in fact you need a DOM/AST representation and compute the comment alignment for consecutive declarations. Is dfmt still working on tokens only?

Hackerpilot commented 8 years ago

Yes. Implementing this will require that I rewrite large parts of dfmt.

Hackerpilot commented 8 years ago

Or add some really ugly code to my pre-parsing step...

MartinNowak commented 8 years ago

Alternative solution, which I found useful in rubocop, is to preserve certain existing formatting, e.g. if you find a comment with additional indentation (aligned to a certain column) you preserve that extra space and could also carry the alignment information over to the following lines.