Skip to content

Missing dead code warning #60342

Open
Open
@eernstg

Description

@eernstg

Consider the following program:

sealed class A {}
class B1 extends A {}
class B2 extends A {}
class C {}

int f(A a) => switch (a) {
  B1() => 1,
  B2() => 2,
  C() => 3,
};

I just learned that the above switch expression does not give rise to a dead code warning. It is guaranteed that when the scrutinee a has static type A, the run-time type of a will match B1() or B2(). This implies that the C() case is dead code, in spite of the fact that there could be an object whose run-time type is a subtype of A and also a subtype of C (class D implements B1, C {} could be declared in any library).

A small experiment shows that the exhaustiveness is recognized already: Comment out C() => 3: No exhaustiveness error is reported for the switch. This implies that all additional cases will be dead.

Could we emit a dead code warning in this case? It seems sound and useful.

Note, though, that the ordering is significant: If the C() => 3 case is moved up to an earlier position then it is not impossible that it could be matched, and hence it isn't dead code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2A bug or feature request we're likely to work onarea-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.model-exhaustivenessImplementation of exhaustiveness checking

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions