sdk icon indicating copy to clipboard operation
sdk copied to clipboard

Detect when an is-expression in an if-statement references an unused private class

Open srawlins opened this issue 1 year ago • 1 comments

If a private class, mixin, or enum is never referenced outside of an is-expression, and is referenced in the right side of an is-expression, and the is-expression is part of the class of expressions we consider in dead code analysis for conditions which are "trivial" (if-statement conditions, while-statement conditions, for-statement conditions, conditional expressions, I think), then the is-expression should be considered trivially false, possibly triggering a dead_code Hint. Here are some examples:

class C {}

void f(Object o) {
  if (o is C || false) {
    print(1); // dead code
  }

  while (o is Future<C>) {
    print(2); // dead code
  }

  o is List<C>
    ? print(3) // dead code
    : print(4);
}

Same for is!

Similar to https://github.com/dart-lang/sdk/issues/40952, but not the same

srawlins avatar Aug 02 '22 23:08 srawlins

There are probably may places you can mention the class, and still use this optimization.

What if a class is definitely uninstantiated (its private, there are no invocations of its generative constructors in the library, and there are no subclasses in the library which are not also definitely uninstantiated), then it is known for sure that the class is empty (there can no actual object instances implementing the interface).

Any check of is C would then definitely be false. It doesn't matter how many other references you have to the class (maybe for its static members, or just other dead code). What matters is that c is C is definitely false.

(Maybe that's just a specialization of an analysis which ensures that no value of that type can flow into the test, which is trivial if no value of that type ever flows anywhere.)

lrhn avatar Aug 03 '22 13:08 lrhn