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.09k stars 1.56k forks source link

[analyzer] incorrectly marking as dead code when accessing record property in ternary #55642

Open mmcdon20 opened 4 months ago

mmcdon20 commented 4 months ago

In the following program, you get an incorrect dead code waring for the code after the ternary expression:

void main() {
  const position = (x: 4, y: 4);
  true ? position.x : position.y;
  // everything below is erroneously marked dead code
  print('this code is reachable');
}

There is no dead code warning if position is a class with x and y fields, so it appears to be specific to records.

class Position {
  const Position({required this.x, required this.y});
  final int x;
  final int y;
}

void main() {
  const position = Position(x: 4, y: 4);
  true ? position.x : position.y;
  // No dead code warning below, working as intended
  print('this code is reachable');
}

However it only seems to fail on variables containing records, it works fine when using record literals in the ternary expression:

void main() {
  true ? (x: 4, y: 4).x : (x: 4, y: 4).y;
  // No dead code warning below, working as intended
  print('this code is reachable');
}
srawlins commented 4 months ago

Can you say what version of Dart you are using? When I plug your first example into dartpad, stable channel, beta channel, or main channel, I only see that position.y is marked as dead.

mmcdon20 commented 4 months ago

@srawlins

Issue is happening with:

Dart SDK version: 3.3.4 (stable) (Tue Apr 16 19:56:12 2024 +0000) on "windows_x64"

and

Dart SDK version: 3.5.0-131.0.dev (dev) (Fri May 3 09:02:58 2024 -0700) on "windows_x64"

I don't see the issue on dartpad either, but it's happening in vscode.

deadcode

srawlins commented 4 months ago

Weeird I can repro this in vscode as well. Thanks for the instructions, great find, and great investigation!