Skip to content

Commit

Permalink
syntax: start using text/tabwriter in the printer
Browse files Browse the repository at this point in the history
The parser aligns comments so that they look nicer on most programs:

        var1="some long value" # var1 comment
        var2=short             # var2 comment

This is calculated while the printer is running. It can't know what the
necessary extra spaces for the current comment are, before it has
printed the following lines.

To work around that, it peeks at the following lines, to figure out what
column an inline comment would be printed on, and figure out the correct
alignment.

This has multiple disadvantages. First, it leads to complex and buggy
code, and makes the core printer much harder to understand. But, most
importantly, it's bad design; what if the next line should be split into
many lines, thus moving the next comment away from the current one?
There are tons of these edge cases.

The way Go's formatter handles this is much nicer. The printer simply
writes "horizontal tab" characters before comments, and once an entire
program has been printed, a second pass is done which replaces the
horizontal tab characters with the correct amount of spaces. This is
much simpler to reason about, and likely less buggy.

What's even better, the second pass is already implemented for us in
text/tabwriter, which we can reuse.

This does make the printer about twice as slow; we'll try to get some of
the performance back in following commits. However, the printer being
better designed and more correct is more important here.

name     old time/op    new time/op    delta
Print-8    4.81µs ± 2%   11.24µs ± 1%  +133.91%  (p=0.002 n=6+6)

name     old alloc/op   new alloc/op   delta
Print-8      344B ± 0%     1056B ± 0%  +206.98%  (p=0.002 n=6+6)

name     old allocs/op  new allocs/op  delta
Print-8      13.0 ± 0%      24.0 ± 0%   +84.62%  (p=0.002 n=6+6)

Fixes mvdan#360.
  • Loading branch information
mvdan committed Mar 11, 2019
1 parent c5d3418 commit 6276884
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 116 deletions.
Loading

0 comments on commit 6276884

Please sign in to comment.