Make formatting code in columns easy by introduction of alignment token ‘’. The token will be used by rustfmt for automatic columns alignment and ignored by rustc.
//Regular style before rustfmt let x\ = 1; let x_multiplied_by_two\ = 2; let x_times_3\ = 3; //Column formatted after rustfmt let x \ = 1; let x_multiplied_by_two\ = 2; let x_times_3 \ = 3;
#Motivation There is a timeless discussion whether some parts of code should be formatted in shape of columns. The gain of wisely used column formatting is readability, but the cost is hard maintenance. Creation and every modification of such code is slow and tedious.
The creators of official Rust coding style guidelines decided to explicitly forbid this technique. Another reason to do this could be impossibility to detect and handle such formatting by rustfmt.
Token driven automation of formatting will bring the best of both worlds: no need for whitespace management, elegant code and fine control over its shape, all in cooperation with rustfmt.
#Detailed design The backslash has currently no meaning outside of text literals, so introduction of ‘’ token won’t break any syntax, but it has to be ignored by rustc.
The columns will be managed uniformly across blocks of code. A block of code will be a series of neighboring lines with the same number of ‘’ tokens in each of them.
let a \ = fun1( \"block 1"); \ // \ block 1 let bbb\ = function2(\"block 1"); let c\ = "block 2"; let d\ = "block 2"; let eee\ = "block 3";
Rustfmt will do the following:
- Identify the first block
- In each line of block find the first ‘’ and remove all spaces right before it
- Get position of the first ‘’ in each line of block and find the highest value
- In each line of block insert spaces right before the first ‘’ so that its position equals the highest value found in point 3
- Repeat steps 2-4 for the second ‘’ in lines of block, then third and so on
- Identify the second block and repeat steps 2-5 for it, then for the third and so on
- It will add another element to already complicated Rust grammar.
- It will take over backslash, which might be needed for a more important syntax extension.
- It will give programmers some freedom of choice of formatting, which always leads to argues.
#Alternatives Things can stay the way they are.
- Should there be inserted at least one space before ‘’ to separate it from the longest line of previous column?
- Should there be inserted exactly one space after ‘’ to separate it from the next column?
- Should the ‘’ token be replaced with '\ ’ (backslash and space)? This will complicate the syntax, but will open the possibility of creation of whole family of autoformatting tokens. For example there could be ‘>’ or ‘~’. I have no idea, what they could be used for.