dart-lang / linter

Linter for Dart.
https://dart.dev/tools/linter-rules
BSD 3-Clause "New" or "Revised" License
628 stars 170 forks source link

[`unnecessary_parenthesis`] false negative in conditional operator #4996

Open FMorschel opened 3 months ago

FMorschel commented 3 months ago

When doing this:

final email = (user.email != null) ? (user.email!) : '';

This is a dumb example, but my point is that in other ternary expressions that I've used, I saw this.

I think that the (user.email!) expression should trigger this as well. I'm not sure because this might be intentional to leave ternary expressions with possible parentheses around all possible results and the test, but it seems strange to me that it doesn't warn me when that is not strictly necessary.

This is a false negative that occurs in any of the three places of a ternary operator.

Originally posted by @FMorschel in https://github.com/dart-lang/linter/issues/4980#issuecomment-2152506202

lrhn commented 3 months ago

It does appear there is an exception for the brances of conditional expressions. Maybe that exception doesn't need to apply to all expressions. A primary + selectorChain may not need parentheses. Maybe suffix/prefix increment operators can be included too, so c ? foo.bar.baz[42].qux++ : x++ won't allow parentheses.

I usually only want parentheses when the syntax contains whitespace, so something with binary operators or prefix operators that are words, fx await. Prefix/suffix operators are flush against the expression, and selector chains only contain spaces inside argument lists, type argument lists and string literals, which are already delimited. Could consider not exempting those from the unnecessary parentheses lint.

(Pet-quixotic-peeve: The ?/: is the conditional operator/expression. It's sometimes called "the ternary conditional operator" or "ternary if", but it's imprecise to just say "the ternary operator". It's a ternary operator, but []= is also a ternary operator in Dart - it takes three operands. This is likely a lost cause, but by golly, I'm going to keep trying!)