dart-lang / sdk

The Dart SDK, including the VM, dart2js, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
9.97k stars 1.54k forks source link

Analyzer not type checking elements in `for in` loops. #48706

Open stereotype441 opened 2 years ago

stereotype441 commented 2 years ago

The following program is accepted by the analyzer but rejected by the front end:

f(List<String> strings) {
  for (int i in strings) { // BUG
    print(i);
  }
}

main() {
  f([]);
}

I'm pretty sure the front end behavior is correct and the analyzer is missing a type check here.

eernstg commented 2 years ago

Right, the <forLoopParts> of a <forElement> are subject to the same static analysis as the corresponding for statement, in the same scope, https://github.com/dart-lang/language/blob/4b709f40886fd15cb35f149bc3d4481368f9c33e/specification/dartLangSpec.tex#L10015:

The same compile-time errors occur for ℓ as the errors that would occur with the corresponding for statement ...

This skips the body (which is some other element), but the static analysis of the body is handled via the normal recursive traversal of that element.

There is a typo in this paragraph (\ell should have been \ell_1 in a couple of places), which is fixed in https://github.com/dart-lang/language/pull/2175.

scheglov commented 2 years ago

Hm... I cannot reproduce.

scheglov@scheglov-macbookpro4:~/Source/Dart/sdk.git/sdk (aa-breaking-changes)$ dart analyze /Users/scheglov/dart/test/bin/test2.dart
Analyzing test2.dart...                0.5s

  error • test2.dart:2:17 • The type 'List<String>' used in the 'for' loop must implement 'Iterable' with a type argument that can be assigned to 'int'. •
          for_in_of_invalid_element_type

1 issue found.
scheglov@scheglov-macbookpro4:~/Source/Dart/sdk.git/sdk (aa-breaking-changes)$ dartanalyzer /Users/scheglov/dart/test/bin/test2.dart
Warning: 'dartanalyzer' is deprecated. Please use 'dart analyze'.
Analyzing /Users/scheglov/dart/test/bin/test2.dart...
  error • The type 'List<String>' used in the 'for' loop must implement 'Iterable' with a type argument that can be assigned to 'int'. • /Users/scheglov/dart/test/bin/test2.dart:2:17 • for_in_of_invalid_element_type
1 error found.
scheglov@scheglov-macbookpro4:~/Source/Dart/sdk.git/sdk (aa-breaking-changes)$ dart --version
Dart SDK version: 2.17.0-edge.3bbde68c4ee67e616ff98101546c229b39b52e54 (be) (Sat Apr 2 17:46:20 2022 +0000) on "macos_arm64"

It worked with a slightly older SDK as well.

srawlins commented 2 years ago

Perhaps a glitch, @stereotype441 ?