Skip to content

Using a late final variable as loop variable for for/in gives incorrect late errors #60359

Open
@lrhn

Description

@lrhn

Example:

void main() {
  late final int c;
  var ints = <int>[1];
  for (c in ints) {
    print(c);
  }
}

This code should be able to run without invalidating any late variable constraints.

The analyzer reports:

The late final local variable is already assigned.

The front end (DDC, Dartpad, main branch) reports:

main.dart:4:8: Error: Can't assign to the final variable 'c'.
  for (c in ints) {
       ^

The analysis should not consider c definitely assigned in the loop header (since it isn't definitely assigned, the example code above would only assign to it once).

The error message suggests that the logic for for/in (which is not well specified to begin with) has some clause saying that the variable must not be final. That would predate late variables, and shouldn't be take verbatim any more.
The variable must be assignable, which means it must:

  • not be const,
  • must not be final unless:
    • it's definitely unassgned, or
    • it's late and potentially unassigned.

Assignment analysis of a for/in (and while) loop should treat the loop variable as:

  • Definitely assigned if it's definitely assigned before the loop.
  • Potentially assigned before the loop assignment if it's not definitely assigned before the loop.
  • Definitely assigned after the loop assignment and after the loop.

Basically, it should work just as if the loop was written as:

void main() {
  late final int c;
  var ints = <int>[1];
  for (final int _$tmp in ints) { // Introduce same context type that `c` would.
    c = _$tmp;
    print(c);
  }
}

which both CFE and analyzer accepts.

(I don't think a late final loop variable is something anyone would ever write, so not a high priority to fix.)

@stereotype441

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3A lower priority bug or feature requestarea-dart-modelFor issues related to conformance to the language spec in the parser, compilers or the CLI analyzer.model-flowImplementation of flow analysis in analyzer/cfe

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions