Skip to content

Commit 25ae05b

Browse files
committed
Allow iterating over generator with void send() type
1 parent 43ee2a7 commit 25ae05b

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/Psalm/Internal/Analyzer/Statements/Block/ForeachAnalyzer.php

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@
6969
use function in_array;
7070
use function is_string;
7171
use function reset;
72+
use function stripos;
7273
use function strtolower;
7374

7475
/**
@@ -702,15 +703,19 @@ public static function checkIteratorType(
702703
if ($has_valid_iterator) {
703704
IssueBuffer::maybeAdd(
704705
new PossiblyInvalidIterator(
705-
'Cannot iterate over ' . $invalid_iterator_types[0],
706+
stripos($invalid_iterator_types[0], 'generator<') === 0
707+
? 'Cannot iterate over generator with non-null send() type ' . $invalid_iterator_types[0]
708+
: 'Cannot iterate over ' . $invalid_iterator_types[0],
706709
new CodeLocation($statements_analyzer->getSource(), $expr),
707710
),
708711
$statements_analyzer->getSuppressedIssues(),
709712
);
710713
} else {
711714
IssueBuffer::maybeAdd(
712715
new InvalidIterator(
713-
'Cannot iterate over ' . $invalid_iterator_types[0],
716+
stripos($invalid_iterator_types[0], 'generator<') === 0
717+
? 'Cannot iterate over generator with non-null send() type ' . $invalid_iterator_types[0]
718+
: 'Cannot iterate over ' . $invalid_iterator_types[0],
714719
new CodeLocation($statements_analyzer->getSource(), $expr),
715720
),
716721
$statements_analyzer->getSuppressedIssues(),
@@ -901,7 +906,11 @@ public static function handleIterable(
901906
&& strtolower($iterator_atomic_type->value) === 'generator'
902907
) {
903908
$type_params = $iterator_atomic_type->type_params;
904-
if (isset($type_params[2]) && !$type_params[2]->isNullable() && !$type_params[2]->isMixed()) {
909+
if (isset($type_params[2])
910+
&& !$type_params[2]->isNullable()
911+
&& !$type_params[2]->isVoid()
912+
&& !$type_params[2]->isMixed()
913+
) {
905914
$invalid_iterator_types[] = $iterator_atomic_type->getKey();
906915
} else {
907916
$has_valid_iterator = true;

tests/Loop/ForeachTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1193,6 +1193,21 @@ function gen() : Generator {
11931193
foreach ($gen as $i) {}
11941194
PHP,
11951195
],
1196+
'generatorWithVoidSend' => [
1197+
'code' => <<<'PHP'
1198+
<?php
1199+
1200+
/**
1201+
* @return Generator<string, int, void, void>
1202+
*/
1203+
function test(): Generator {
1204+
yield 'test' => 1;
1205+
}
1206+
1207+
foreach (test() as $_) {
1208+
}
1209+
PHP,
1210+
],
11961211
'nullableGenerator' => [
11971212
'code' => <<<'PHP'
11981213
<?php

0 commit comments

Comments
 (0)