avh4 / elm-format

elm-format formats Elm source code according to a standard set of rules based on the official Elm Style Guide
BSD 3-Clause "New" or "Revised" License
1.31k stars 147 forks source link

Automatically add parens for certain binary operator combinations #375

Open avh4 opened 7 years ago

avh4 commented 7 years ago

We can't in general know the operator precedence because that would break the goal of being able to format any code consistently without having to have more info from the context. But maybe for operators that are defined in core, we could do special handling given the known precendence and associativity.

One common example is people using && and ||. We could detect this and add the recommended parentheses.

screen shot 2017-06-02 at 4 34 41 pm
rlefevre commented 4 years ago

Is this proposal only for multi-line expressions? Or do you suggest also adding parentheses to single line expressions like

if x > 0 && x < 4 then

or

if x == 1 && y == 2 then

?

It's not clear to me because I believe that precedence in such expressions is well known as it is the same in almost all programming languages. I may underestimate though the issue this causes to beginners, but then where to put the limit? For example certainly precedence of multiplication over addition is well known and we might not want either to put parentheses around all expressions before and after |>.

Therefore if the proposal also applies to single-line expressions, the first step seems to consist of finding a consensus about what are the "recommended parentheses".

If this is only for multi-line expressions, why not use the known precedence to format the expression as:

if
    relevantItems == []
        && config.notFoundStyles == []
        && config.notFoundStyles == []
        && config.notFoundStyles == []
then
    style config.notFoundHidden
else
    style (viewStyles config)

instead of adding parentheses?

harrysarson commented 4 years ago

I think that adding parentheses is more useful where the operator precedence is potentially confusing. For example:

True || False && False || False

gives True as it is equivilent to

True || (False && False) || False

but that isn't clear without parentheses.


Maybe this is tangential to the issue being discussed here though.