dart-lang / linter

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

[`unnecessary_parenthesis`] false negative inside switch expressions #4980

Open FMorschel opened 1 month ago

FMorschel commented 1 month ago

Describe the issue unnecessary_parenthesis false negative.

When having a code like:

T a<T>(int x, bool test) {
  switch (x) {
    case 0:
      return test ? 1 : 2 as T;
    default:
      return 3 as T;
  }
}

The return of case 0 warns: A value of type 'Object?' can't be returned from the function 'a' because it has a return type of 'T'.

So in that case, we need to wrap that in parentheses.

return (test ? 1 : 2) as T;

This doesn't throw anymore.

When changing to the new pattern switch syntax, we can cast at the end as follows:

T a<T>(int x, bool test) {
  return switch (x) {
    0 => (test ? 1 : 2),   // Not triggering
    _ => 3,
  } as T;
}

And now that is not needed anymore and should trigger the lint.

FMorschel commented 3 weeks ago

I'm not sure that this is the same, but I've also seen:

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.

If you agree that this is also another false-negative I can create another issue.

Edit

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

bwilkerson commented 4 days ago

Related to https://github.com/dart-lang/linter/issues/4996