Integrated code formatter

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Jan 17 22:19:51 UTC 2022


On Mon, Jan 17, 2022 at 09:46:08PM +0000, forkit via Digitalmars-d wrote:
> So I use clang-format extensively...like all the time.
> 
> It makes such a difference, I can't imagine programming without it
> anymore.
> 
> But D doesn't have something integrated like this.
> 
> I am aware of dfmt.. but even on it's github page it says "dfmt is
> beta quality."

So?  You can still use it.


> I wonder if it isn't time a code formatter for D became a more
> integrated product, into the release itself, so that people like me
> can actually rely on it to work as expected, and also, so that the
> formatter's needs were considered whenever making changes to D.
> 
> Or is D code now so variable and complex, that no formatter can
> reliably format it?

Code formatting is an art, not a science. There are many cases where I
would NOT want an automatic formatter to mess with my code because it
would make it less readable.

For example, here's a snippet of an actual unittest in one of my
projects:

    auto expected = [
        [  1,  1,  Sqrt2, 1 ],
        [  1, -1,  Sqrt2, 1 ],
        [ -1,  1,  Sqrt2, 1 ],
        [ -1, -1,  Sqrt2, 1 ],

        [          1,  (1+Sqrt2),  0, 1 ],
        [          1, -(1+Sqrt2),  0, 1 ],
        [         -1,  (1+Sqrt2),  0, 1 ],
        [         -1, -(1+Sqrt2),  0, 1 ],
        [  (1+Sqrt2),          1,  0, 1 ],
        [  (1+Sqrt2),         -1,  0, 1 ],
        [ -(1+Sqrt2),          1,  0, 1 ],
        [ -(1+Sqrt2),         -1,  0, 1 ],
    ];

I would NOT want an auto code formatter to go, "hey, you have all those
ugly redundant spaces, let's compress them to a single space!", or "hey,
you can fit more array elements per line in your outer array, let's save
some space!" -- because that would destroy the visual symmetry that
actually makes this code readable.  If this were formatted the more
usual way, it would become much less readable because its large-scale
structure would be obscured.

But in other instances, I *would* want my arrays to be formatted more
compactly.  No automatic formatter can reliably guess when to format it
one way vs. another in such cases, and I'd prefer to just do it myself
(and not have the computer screw things up afterwards).

(Yes I know some code formatters have tags to suppress automatic
formatting, etc., but seriously, why do I need to explicitly ask the
computer not to do something I didn't want it to do in the first place?)

//

That said, if an automatic formatter works for you, why not give dfmt a
spin?  Don't be intimidated by the "beta" label (what does that even
mean anyway); try it out and see if it's really as bad as you imagine it
to be.  You might be pleasantly surprised.


T

-- 
If I were two-faced, would I be wearing this one? -- Abraham Lincoln


More information about the Digitalmars-d mailing list