Skip to content

Commit ecc44da

Browse files
committed
Quantified atom that can match empty string does not make the match non-empty
Amp-Thread-ID: https://ampcode.com/threads/T-01a177b5-960f-71d2-a3e2-fa7649f39d2c
1 parent 16529f5 commit ecc44da

2 files changed

Lines changed: 22 additions & 2 deletions

File tree

‎src/Type/Regex/RegexGroupParser.php‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -537,7 +537,9 @@ private function walkGroupAst(
537537
$walkResult = $walkResult->inOptionalQuantification(true);
538538
}
539539

540-
if (!$walkResult->isInOptionalQuantification()) {
540+
// repeating an atom that might match an empty string might match an empty string too
541+
$atomNonFalsy = false;
542+
if (!$walkResult->isInOptionalQuantification() && !$this->isMaybeEmptyNode($children[0], $patternModifiers, $atomNonFalsy)) {
541543
if ($min >= 1) {
542544
$walkResult = $walkResult->nonEmpty(TrinaryLogic::createYes());
543545
}
@@ -767,7 +769,8 @@ private function isMaybeEmptyNode(RegexNode $node, string $patternModifiers, boo
767769
[$min] = $this->getQuantificationRange($node);
768770

769771
if ($min > 0) {
770-
return false;
772+
$atomNonFalsy = false;
773+
return $this->isMaybeEmptyNode($node->getChildren()[0], $patternModifiers, $atomNonFalsy);
771774
}
772775

773776
if ($min === 0) {

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1134,3 +1134,20 @@ function testDuplicateNamesInternalOption(string $s): void {
11341134
assertType('list<array<string>>', $matches);
11351135
}
11361136
}
1137+
1138+
function testQuantifiedMaybeEmptyAtom(string $s): void {
1139+
// from PCRE2 testdata/testinput6
1140+
if (preg_match('/(abc|)+/', $s, $matches)) {
1141+
assertType("array{string, string}", $matches);
1142+
}
1143+
1144+
// from PCRE2 testdata/testinput6
1145+
if (preg_match('/^(){3,5}/', $s, $matches)) {
1146+
assertType("array{string, string}", $matches);
1147+
}
1148+
1149+
// from PCRE2 testdata/testinput1
1150+
if (preg_match('/((a|)+)+Z/', $s, $matches)) {
1151+
assertType("array{non-falsy-string, string, string}", $matches);
1152+
}
1153+
}

0 commit comments

Comments
 (0)