dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.26k stars 1.58k forks source link

[analyzer] mark `default` as dead code if the others cases are exhaustive #51503

Open asashour opened 1 year ago

asashour commented 1 year ago
enum E { a, b }

void f(E e) {
  switch (e) {
    case E.a:
      break;
    case E.b:
      break;
    default:
      print('dead code');
  }
}

The default clause should be marked as dead code.

incendial commented 1 year ago

But if the default: becomes empty and the enum gets updated - won't it create a potential bug?

asashour commented 1 year ago

The dead code starts from the beginning of default:, so even if it has no statements, the warning would be shown.

The user has to remove the default: .... clause, or change the exhaustiveness of the enum or the switch cases.

If dead code is not triggered, because of the fear that the user would change the code later, then the other dead code should not trigger because the user can change the condition, and this makes the whole dead code not a correct decision, e.g.

void f() {
  var x = false;
  if (x) {
    print('dead');
  }
}

currently triggers dead code, without a concern that false can be true if the user changes it later.

Also, I think the main point of exhaustiveness applies to other areas, e.g. patterns.

incendial commented 1 year ago

currently triggers dead code, without a concern that false can be true if the user changes it later.

If we refer to real world examples, don't you think that a local variable declaration and a global enum declaration (which can be in another file / module from the place it's used) are completely different things in terms of "I see how this change will affect other parts of my codebase"?

Edit: asking mostly out of curiosity

bwilkerson commented 1 year ago

@stereotype441 @johnniwinther

Do we know yet how exhaustiveness checking and flow analysis will treat the default clause in a switch statement?