Skip to content

Commit 2939435

Browse files
committed
Do not infer preg_match() shapes for branch reset groups outside of the only top level alternation
Amp-Thread-ID: https://ampcode.com/threads/T-01a177b5-960f-71d2-a3e2-fa7649f39d2c
1 parent 4913e74 commit 2939435

4 files changed

Lines changed: 40 additions & 0 deletions

File tree

‎src/Type/Php/RegexArrayShapeMatcher.php‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,21 @@ private function matchRegex(string $regex, ?int $flags, TrinaryLogic $wasMatched
159159
return null;
160160
}
161161

162+
if (
163+
$regexGroupList->hasGroupResettingGroupCounter()
164+
&& (
165+
$matchesAll
166+
|| $onlyOptionalTopLevelGroup !== null
167+
|| $onlyTopLevelAlternation === null
168+
|| $wasMatched->no()
169+
|| $this->containsUnmatchedAsNull($flags, $matchesAll)
170+
)
171+
) {
172+
// groups in a branch reset (?|...) share offsets, which is only modelled
173+
// when its alternation is the only top level alternation
174+
return null;
175+
}
176+
162177
if (
163178
!$matchesAll
164179
&& $wasMatched->yes()

‎src/Type/Regex/RegexGroupList.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,17 @@ public function hasDuplicateNamesOutsideOfAlternationBranches(?RegexAlternation
178178
return false;
179179
}
180180

181+
public function hasGroupResettingGroupCounter(): bool
182+
{
183+
foreach ($this->groups as $captureGroup) {
184+
if ($captureGroup->resetsGroupCounter()) {
185+
return true;
186+
}
187+
}
188+
189+
return false;
190+
}
191+
181192
public function getOnlyTopLevelAlternation(): ?RegexAlternation
182193
{
183194
$alternation = null;

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,3 +226,10 @@ function markVerbs(string $s): void {
226226
assertType("non-empty-list<array{0: string, MARK?: 'A'|'B'}>", $matches);
227227
}
228228
}
229+
230+
function testBranchReset(string $s): void {
231+
// from PCRE2 testdata/testinput2
232+
if (preg_match_all('/(?|(abc)|(xyz))/', $s, $matches)) {
233+
assertType('array<list<string>>', $matches);
234+
}
235+
}

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1168,3 +1168,10 @@ function testBackreferences(string $s): void {
11681168
assertType("array{non-falsy-string, non-falsy-string, string}", $matches);
11691169
}
11701170
}
1171+
1172+
function testBranchResetNotInOnlyTopLevelAlternation(string $s): void {
1173+
// from PCRE2 testdata/testinput2
1174+
if (preg_match('/(x)(?|(abc)|(xyz))(x)/', $s, $matches)) {
1175+
assertType('array<string>', $matches);
1176+
}
1177+
}

0 commit comments

Comments
 (0)