Skip to content

Analyzer: Consider noting failed null promotion in error messages #42388

Closed
@leafpetersen

Description

@leafpetersen

Based on a real example encountered by @yjbanov , consider this example:

void foo(int y) {
  int? x;
  for(int i = 0; i < y; i++) {
    switch(i) {
      case 0:
      x ??= 3;
      x.isEven;
      break;
      default:
      (() { x ??= 4;})();
    }
  }
}

The call to x.isEven is an error because the x ??= 3 can't promote, because there's an assignment to x in a closure which could be live on the back edge of the loop. This is easy to miss though, and so it is surprising that x.isEven is an error. The error message that the analyzer gives is correct, but doesn't help the user understand why promotion is not kicking in:

 error • An expression whose value can be 'null' must be null-checked before it can be dereferenced. • /Users/leafp/tmp/test.dart:9:7 • unchecked_use_of_nullable_value

It seems like at least for error messages around nullability, it might sometimes be feasible to notice that the variable in question was not able to be promoted, and give notice of that in some way, e.g something like:

 error • A variable which was declared nullable could not be determined to be non-null because it is written to in a closure, and must be null-checked before it can be dereferenced. • /Users/leafp/tmp/test.dart:9:7 • unchecked_use_of_nullable_value

Not sure if we have enough information lying around to give this kind of feedback, but could be nice if so.

Metadata

Metadata

Assignees

No one assigned

    Labels

    NNBDIssues related to NNBD ReleaseP2A bug or feature request we're likely to work onlegacy-area-analyzerUse area-devexp instead.type-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions