This is an interesting perspective from one of the authors of Go about Go’s formatter tool (akin to crystal tool format
):
For example, most people think that we format Go code with gofmt
to make code look nicer or to end debates among team members about program layout. But the most important reason for gofmt
is that if an algorithm defines how Go source code is formatted, then programs, like goimports
or gorename
or go
fix
, can edit the source code more easily, without introducing spurious formatting changes when writing the code back. This helps you maintain code over time.
https://research.swtch.com/vgo-eng
via simonwillison.net
I actually hadn’t considered this, but it makes a lot of sence. My ignorance may be because there are not (yet) many tools for automatic code editing in Crystal, so there’s not too much practical use for it.
9 Likes
This is such an important aspect of tool development, even though it rarely comes to mind when people think about formatters. Without one, you have to reach for all kinds of unreliable and unmantainable hacks to try and keep a cohesive style after programmatically editing a source file. If your code base is already committed to a formatting tool, on the other hand, you can just parse the code into a concrete syntax tree, do some modifications, and unparse it back! It transforms the huge effort of developing, say, a static analysis tool into a somewhat trivial task.
1 Like
Interesting… kind of a jury-rigged way of achieving homoiconicity without s-expressions.
2 Likes
Crystal::ToSVisitor
, the internal class that implements macro interpolation, does some of this already. Unfortunately it doesn’t honor all formatting rules (e.g. no newlines between consecutive classes inside an Expressions
node) so we still need a separate formatter