Skip to content

Keep optional groups optional within a matched regex alternation branch - #6596

Merged
ondrejmirtes merged 1 commit into
2.2.xfrom
issue-15297
Sep 25, 2026
Merged

ondrejmirtes merged 1 commit into
2.2.xfrom
issue-15297

Conversation

@ondrejmirtes

Copy link
Copy Markdown
Member

Closes phpstan/phpstan#15297

The reported errors show up when the analysed PHP version is below 7.4 (e.g. PHP 7.2/7.3 on the playground). Two inaccuracies in RegexArrayShapeMatcher caused them:

  • Optional groups in the matched alternation branch were forced non-optional. For the tagged union of a single top-level alternation, every group of the matched branch was forceNonOptional()-ed, which also dropped its own optional quantifier, e.g. (?:-(?P<bar1>[0-9]+))?. PHP omits such a trailing unmatched group (without PREG_UNMATCHED_AS_NULL, or on 7.2/7.3), but PHPStan inferred bar1: numeric-string as always present. The matched branch's groups are now only forced out of the alternation's optionality: they remain optional when they, or a parent within the same branch, are optionally quantified.
  • PREG_UNMATCHED_AS_NULL on PHP 7.2 and 7.3 was modelled as no flag at all, i.e. '' for unmatched groups. Those versions already report an unmatched group followed by a matched one as null; only trailing unmatched groups are omitted. Verified against php:7.2-cli and php:7.3-cli.

On PHP 7.3 the reproducer now reports one remaining error which is a true positive: when foo1 is null the second branch matched, so $matches["foo2"] always exists and ?? "" is dead. PHP 7.4+ was and remains error-free.

Tests:

  • nsrt/bug-15297.php – flag-less shapes (also (?:(a))?(b)|(c), previously inferred as always 'a')
  • Bug15297Php73Test – PHP 7.3 shapes with PREG_UNMATCHED_AS_NULL
  • NullCoalesceRulePhp73Test – the playground reproducer verbatim on PHP 7.3

🤖 Generated with Claude Code

https://claude.ai/code/session_01KjXHtRyzsYF9xktijyaRBr

When building the tagged union for a single top-level alternation, the
groups of the matched branch were forced non-optional, which also dropped
their own optional quantifiers, e.g. `(?:-(?P<bar>\d+))?`. Such a group
is now only forced out of the alternation's optionality.

With PREG_UNMATCHED_AS_NULL on PHP 7.2 and 7.3, an unmatched group
followed by a matched one is reported as null, not as an empty string.
Only the trailing unmatched groups are omitted there.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KjXHtRyzsYF9xktijyaRBr
@ondrejmirtes
ondrejmirtes merged commit 68c2e4e into 2.2.x Sep 25, 2026
507 of 508 checks passed
@ondrejmirtes
ondrejmirtes deleted the issue-15297 branch September 25, 2026 20:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant