Skip to content

Resolve an unconstrained template argument from all its bounds - #7227

Merged
ondrejmirtes merged 1 commit into
2.3.xfrom
template-bound-solving
Nov 27, 2026
Merged

ondrejmirtes merged 1 commit into
2.3.xfrom
template-bound-solving

Conversation

@ondrejmirtes

Copy link
Copy Markdown
Member

When nothing was inferred for a generic object's template, TemplateArgumentSolver took the first covariant upper bound it was sent to. The result depended on call order, and the later call got a false argument.type:

/** @param Box<covariant int|string> $b */ function a(Box $b): void {}
/** @param Box<covariant int|bool> $b */   function b(Box $b): void {}

$box = new Box();
a($box);
b($box); // Parameter #1 $b of function b expects Box<covariant bool|int>, Box<int|string> given.
         // with the calls swapped, a() is reported instead; Box<int> satisfies both

The solver now follows the order of JLS 18.4:

  1. An invariant send that accepts what was inferred resolves it, as before.
  2. Otherwise lower bounds (contravariant sends, values passed in) give their union.
  3. Otherwise the argument is the intersection of every covariant upper bound. Box<covariant Countable> and Box<covariant Traversable> now give Box<Countable&Traversable> instead of reporting the second call.
  4. If the upper bounds contradict each other (their intersection is never), the first one stands, so the conflicting call is still reported.

Step 2 changes one existing expectation in nsrt/template-argument-multiple-sites.php (invariantIntoCovariant). There $a->add(1) and $b->add(2) are lower bounds, and takesBoxOfInt($z) is an upper bound. $a is now Coll<1|2> instead of Coll<int>. Without the takesBoxOfInt() call it already was Coll<1|2>, so a later covariant consumer no longer widens it. It is also what a lone $box->add(1) gives (Box<1>).

The solver is PHP-only (the turbo extension calls into it), so there is no C++ change.

A site with nothing inferred took its first covariant upper bound, so
passing a fresh Box to a(Box<covariant int|string>) and then to
b(Box<covariant int|bool>) inferred Box<int|string> and reported b().
Like JLS 18.4, lower bounds now come first, and failing them the
argument is the intersection of every upper bound. Contradicting upper
bounds keep the first one, so the conflicting call is still reported.

Amp-Thread-ID: https://ampcode.com/threads/T-01a17eac-1199-74a6-b3f7-dfbd8a084465
@ondrejmirtes
ondrejmirtes merged commit 0ed534e into 2.3.x Nov 27, 2026
878 of 917 checks passed
@ondrejmirtes
ondrejmirtes deleted the template-bound-solving branch November 27, 2026 13:49
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