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.03k stars 1.55k forks source link

False positive `dead_code` lint for pattern matching empty list by constant pattern followed by null check pattern #54827

Open maBarabas opened 6 months ago

maBarabas commented 6 months ago
dart info ``` #### General info - Dart 3.2.0 (stable) (Tue Nov 14 18:26:59 2023 +0000) on "linux_x64" - on linux / Linux 6.7.1-zen1-1-zen #1 ZEN SMP PREEMPT_DYNAMIC Sun, 21 Jan 2024 22:13:51 +0000 - locale is en_GB.UTF-8 #### Project info - sdk constraint: '>=3.2.0 <4.0.0' - dependencies: flutter, flutter_riverpod, freezed, freezed_annotation, gap, go_router, logging, material_symbols_icons, protobuf, riverpod_annotation, rxdart, sentry_flutter, sentry_logging, stream_channel - dev_dependencies: build_runner, custom_lint, flutter_lints, flutter_test, riverpod_generator, riverpod_lint - elided dependencies: 1 #### Process info | Memory | CPU | Elapsed time | Command line | | -----: | ---: | -----------: | ------------------------------------------------------------------------------------------ | | 63 MB | 0.0% | 05:44:01 | dart devtools --machine | | 590 MB | 0.6% | 16:15 | dart language-server --client-id=Android-Studio --client-version=AI-231.9392.1 --protocol=analyzer | | 74 MB | 0.0% | 05:46:15 | flutter_tools.snapshot daemon ```

dartpad

void main() {
  print('[]: ${bug([])}');
  print('[1]: ${bug([1])}');
  print('null: ${bug(null)}');
}

List<String>? bug(List<int>? maybeList) {
  return switch(maybeList) {
      [] => null,
      final list? => ['dead code'],
      _ => null,
  };
}

Above code causes the dart analyzer to get confused about the second pattern (final list?):

Dead code.
This case is covered by the previous cases.

When running the program, it works as expected:

[]: null
[1]: [dead code]
null: null
ewertonls commented 4 months ago

if you do

switch(maybeList) {
      [] || null => null,
      _ => ['dead code'],
  };

the _ => ['dead code'], will be dead code too, even though it's not