Skip to content

Commit 85e691f

Browse files
committed
MARK in preg_match_all() with PREG_PATTERN_ORDER is an array of marks keyed by match index
Amp-Thread-ID: https://ampcode.com/threads/T-01a177b5-960f-71d2-a3e2-fa7649f39d2c
1 parent f5632ba commit 85e691f

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

‎src/Type/Php/RegexArrayShapeMatcher.php‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,9 +310,18 @@ private function buildArrayType(
310310
foreach ($markVerbs as $mark) {
311311
$markTypes[] = new ConstantStringType($mark);
312312
}
313+
$markType = TypeCombinator::union(...$markTypes);
314+
if ($matchesAll && $this->containsPatternOrder($flags)) {
315+
// marks are keyed by the index of the match that set them, matches without a mark are left out
316+
$markType = new IntersectionType([
317+
new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $markType),
318+
new NonEmptyArrayType(),
319+
]);
320+
}
321+
313322
$builder->setOffsetValueType(
314323
$this->getKeyType('MARK'),
315-
TypeCombinator::union(...$markTypes),
324+
$markType,
316325
true,
317326
);
318327
}

‎tests/PHPStan/Analyser/nsrt/preg_match_all_shapes.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,3 +215,14 @@ function setOrderOptionalGroupFollowedByMatchedGroup(string $s): void {
215215
assertType("non-empty-list<array{0: string, 1?: ''|'a', 2?: 'b'}>", $matches);
216216
}
217217
}
218+
219+
function markVerbs(string $s): void {
220+
// from PCRE2 testdata/testinput1
221+
if (preg_match_all('/A(*:A)B|XX(*:B)Y/', $s, $matches)) {
222+
assertType("array{0: non-empty-list<string>, MARK?: non-empty-array<int<0, max>, 'A'|'B'>}", $matches);
223+
}
224+
225+
if (preg_match_all('/A(*:A)B|XX(*:B)Y/', $s, $matches, PREG_SET_ORDER)) {
226+
assertType("non-empty-list<array{0: string, MARK?: 'A'|'B'}>", $matches);
227+
}
228+
}

0 commit comments

Comments
 (0)