Repository navigation
fix(templates): trait method params use the types given to @use - #13429
Conversation
…#4538 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Behaviour change
|
✅ Performance: unchanged · Types: decreased
How to read this table
✅ laravel: issues +6 −8Memory 1 751 → 1 751 MB (<0.1 %) · Wall 93.7 → 94.4 s (+0.8 %) Weighted 53 462 → 53 450 (−12, −0.02 %): L6 −2
Changed in place (3); @@ 2 places MixedArgumentTypeCoercion @@
src/Illuminate/Collections/Traits/EnumeratesValues.php:309
src/Illuminate/Collections/Traits/EnumeratesValues.php:547
- Argument 1 of Collection::valueRetriever expects callable[impure]|null|string, but parent type (TValue:{self} as mixed)|callable[impure](TValue:{self} as mixed, TKey:{self} as array-key):bool|string provided
- Argument 1 of LazyCollection::valueRetriever expects callable[impure]|null|string, but parent type (TValue:{self} as mixed)|callable[impure](TValue:{self} as mixed, TKey:{self} as array-key):bool|string provided
+ Argument 1 of Collection::valueRetriever expects callable[impure]|null|string, but parent type (TValue:Collection as mixed)|callable[impure](TValue:Collection as mixed, TKey:Collection as array-key):bool|string provided
+ Argument 1 of LazyCollection::valueRetriever expects callable[impure]|null|string, but parent type (TValue:LazyCollection as mixed)|callable[impure](TValue:LazyCollection as mixed, TKey:LazyCollection as array-key):bool|string provided
@@ src/Illuminate/Collections/Traits/EnumeratesValues.php:352 PossiblyInvalidArgument @@
- Argument 1 of Collection::filter expects callable[impure](TValue:Collection as mixed, TKey:Collection as array-key):bool|null, but possibly different type Closure[impure]|callable[impure](TValue:EnumeratesValues as mixed, TKey:EnumeratesValues as array-key):bool|null|string provided
- Argument 1 of LazyCollection::filter expects callable[impure](TValue:LazyCollection as mixed, TKey:LazyCollection as array-key):bool|null, but possibly different type Closure[impure]|callable[impure](TValue:EnumeratesValues as mixed, TKey:EnumeratesValues as array-key):bool|null|string provided
+ Argument 1 of Collection::filter expects callable[impure](TValue:Collection as mixed, TKey:Collection as array-key):bool|null, but possibly different type Closure[impure]|callable[impure](TValue:Collection as mixed, TKey:Collection as array-key):bool|null|string provided
+ Argument 1 of LazyCollection::filter expects callable[impure](TValue:LazyCollection as mixed, TKey:LazyCollection as array-key):bool|null, but possibly different type Closure[impure]|callable[impure](TValue:LazyCollection as mixed, TKey:LazyCollection as array-key):bool|null|string providedRemoved (2)
✅ tempest: issues +10 −10Memory 895 → 895 MB (+0.0 %) · Wall 26.8 → 27.1 s (+1.0 %)
Changed in place (5); @@ 5 places PossiblyInvalidArgument @@
packages/support/src/Arr/ManipulatesArray.php:300
packages/support/src/Arr/ManipulatesArray.php:312
packages/support/src/Arr/ManipulatesArray.php:324
packages/support/src/Arr/ManipulatesArray.php:336
packages/support/src/Arr/ManipulatesArray.php:348
- …key, mixed>, but possibly different type (ImmutableArray<TKey:{self} as array-key, TValue:{self} as mixed>&static)|(array<TKey:{self} as array-key, TValue:{self} as mixed>) provided
- …key, mixed>, but possibly different type (MutableArray<TKey:{self} as array-key, TValue:{self} as mixed>&static)|(array<TKey:{self} as array-key, TValue:{self} as mixed>) provided
+ …key, mixed>, but possibly different type (ImmutableArray<TKey:ImmutableArray as array-key, TValue:ImmutableArray as mixed>&static)|(array<TKey:ImmutableArray as array-key, TValue:ImmutableArray as mixed>) provided
+ …key, mixed>, but possibly different type (MutableArray<TKey:MutableArray as array-key, TValue:MutableArray as mixed>&static)|(array<TKey:MutableArray as array-key, TValue:MutableArray as mixed>) providedhead 0bbfecf · base 96953a3 (merge-base) · workflow run |
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
# Conflicts: # tests/Template/TraitTemplateTest.php
|
Checked against current master ( Not changed, read only: finding 1 (the perf run's nine new reports on laravel Ran: the three cases of the PR on master. No code change pushed. |
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
orklah
left a comment
There was a problem hiding this comment.
Thanks, the binding fixes #4538 and more than the PR's cases: I checked locally that nested traits (@use Inner<U> inside a trait used with Outer<DateTime>), as aliases, insteadof, a class template forwarded with @use Fwd<X> and list<T> params all stop reporting on this branch, and the three new cases fail on the merge base and pass on the head.
One regression, though, visible in the perf report: laravel loses four InvalidTemplateParam (EnumeratesValues.php:232/301/539/921, "Template param TValue of ...EnumeratesValues is marked covariant and cannot be used here"). Those are true positives: @param (callable(TValue, TKey): bool)|TValue|string $key uses the trait's @template-covariant TValue in a parameter. The covariance check of $param_type->check() now runs on the rebound type, so it no longer sees the trait's template, even with a concrete @use:
<?php
/** @template-covariant TValue */
trait EV {
/** @param TValue $v */
public function has($v): bool { return (bool) $v; } // master: InvalidTemplateParam, branch: no issue
}
class Coll {
/** @use EV<int> */
use EV;
}The same happens with @template-covariant TValue on the class and @use EV<TValue> (the laravel shape).
Please bind after the check instead (see the inline comment), and add both snippets above as invalid cases expecting InvalidTemplateParam. I tried that move locally: both covariance cases report again, and the three new cases plus the nested/forwarded ones still pass.
The other perf deltas are fine: the 9 laravel additions and the 16/16 tempest changes are the same issues on the same lines, now naming the using class's template (TValue:Illuminate\Support\Collection instead of TValue:...\EnumeratesValues); the 7 removed BuildsQueries InvalidArgument with stdClass are false positives fixed (Query\Builder uses @use BuildsQueries<\stdClass>).
Nit: traitMethodParamIsNotAcceptedWhereTheUseTypeDoesNotFit could pin the message ('error_message' => 'Argument 1 of Bar::b expects stdClass, but DateTime provided') rather than the bare InvalidArgument substring.
| } | ||
| } | ||
|
|
||
| $param_type = $this->bindTraitTemplatesToUse($codebase, $storage, $context, $param_type); |
There was a problem hiding this comment.
Move this call below the if ($function_param->type_location && !$inherited_type) { ... $param_type->check(...) ... } block, just before addParentNodes(). check() validates the docblock as written in the trait (template covariance among other things), so it has to see the trait's own templates; the binding is only needed for the type the body is analysed with.
…use's templates vimeo#4538 check() validates the docblock as written in the trait (template covariance among other things), so it has to see the trait's own templates; the binding is only needed for the type the body is analysed with. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Addressed the review (
Run: the five cases above singly, phpcs, one full self-analysis (clean). Not run: the rest of |
orklah
left a comment
There was a problem hiding this comment.
Thanks, the move is right: both covariance cases report again, and the perf deltas are now only renames plus the BuildsQueries<\stdClass> false positives that are fixed.
Binding the parameter types adds new false positives, though; master reports nothing on these:
<?php
/** @template T */
trait Red {
/** @param T $x */
public function f($x): string {
if (is_string($x)) { // RedundantConditionGivenDocblockType (RedStr), DocblockTypeContradiction (RedInt)
return $x; // NoValue
}
return 'other';
}
}
final class RedStr { /** @use Red<string> */ use Red; }
final class RedInt { /** @use Red<int> */ use Red; }
/** @template T */
trait Ref {
/** @param T $d */
public function r(&$d): void { echo 'x'; } // ReferenceConstraintViolation
}
final class RefCls { /** @use Ref<int> */ use Ref; }- By-reference parameters:
checkByRefParams()(FunctionLikeAnalyzer.php~2451) compares the bound variable against the unbound$param->out_type ?: $param->type, sor(&$d)reportsReferenceConstraintViolationeven with an empty body. The by-ref constraint, and@param-out, need the same binding. - Narrowing in the body:
is_string($x)now reportsRedundantConditionGivenDocblockTypefor one user andDocblockTypeContradiction+NoValuefor the other. A generic trait legitimately branches on its template's type, so these should stay quiet. One option is to keep a template type whose upper bound is the@usetype instead of replacing it with the concrete type, if that still fixes #4538.
Please add both snippets as valid cases.
… parameter The parameter keeps the trait's own templates, so a generic trait can still branch on its template and take it by reference; only the type of an argument given to a call is bound to the type given to `@use`. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Pushed 1a0f814. The parameter types are no longer bound: they keep the trait's own templates, which fixes both false positives from the review (
Run: the new and the existing trait template cases one by one, phpcs, a full self-analysis (clean). Not run: the whole suite and the perf report, so the laravel |
orklah
left a comment
There was a problem hiding this comment.
Thanks, both snippets from my review now pass. Binding the argument type moves the false positives to calls, though; master reports nothing on this:
/** @template T */
trait Red {
/** @param T $x */
public function f($x): void {
if (is_string($x)) { takesString($x); } // InvalidScalarArgument "expects string, but int provided" (RedInt)
if (is_int($x)) { takesInt($x); } // InvalidScalarArgument "expects int, but string provided" (RedStr)
}
}
final class RedStr { /** @use Red<string> */ use Red; }
final class RedInt { /** @use Red<int> */ use Red; }- Narrowing: the binding ignores the narrowed type. The bound type also flows back into the body: after
takesString($x)under@use Leak<string>,is_string($x)reportsRedundantCondition. - Template inference: tempest gets 20 new
InvalidArgument(e.g.ManipulatesArray.php:110). The called function's templates are inferred from the unbound$this->value(TValue:ManipulatesArray) while the callable argument is bound (TValue:ImmutableArray). Minimal repro: a traitManip<TKey, TValue>with/** @param callable(TInit|TRet, TValue, TKey): TRet $callback */ reduce()callingred($this->value, $callback, $initial), used as@use Manip<TKey, TValue>by a templated class. - The
BuildsQueries<\stdClass>false positives that the previous version fixed are no longer in the perf delta.
Please add the narrowing call and the reduce shape as valid cases. Binding has to leave narrowed types alone, and has to apply to the parameter types the called function infers as well as to the argument. Nit: there's a leftover blank line before addParentNodes().
…arameter type of a call too - `is_string($x)` on a trait template `T` gives `T as string`; binding it to `@use Red<int>` replaced the whole thing by `int` and reported `takesString($x)`. A template narrowed by a check is left alone. - The parameter type a called function infers from an argument of a trait template type (`red($this->value, $callback, ...)`) is bound like the argument, so the callable's `TValue` is not compared with the trait's `TValue`. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Pushed c4c3973 for the review of 1a0f814. Probed first on the previous head and on master (
Run: the new cases and the 8 earlier cases of this PR, single; self-analysis clean. Not run: the tempest/laravel perf comparison (no local copy of those projects), the full suite (CI). |
|
Local benchmark run for the triage report's perf findings (the benchmark runner itself is not available to me): Psalm on
Limits: tempest, which the review cites, is not covered. Not run: the full suite (CI). |
orklah
left a comment
There was a problem hiding this comment.
Thanks, the narrowed calls, the reduce inference and BuildsQueries<\stdClass> are all good now.
One point is left: the bound type still flows back into the body when the call comes before the check. Master reports nothing on this:
/** @template T */
trait Leak {
/** @param T $x */
public function h($x): string {
ts($x);
if (is_string($x)) { return $x; } // RedundantCondition
return 'o';
}
/** @param T $x */
public function h2($x): void {
ts($x);
if (is_int($x)) { ti($x); } // TypeDoesNotContainType, NoValue
}
}
final class LeakStr { /** @use Leak<string> */ use Leak; }verifyType() now passes the bound $input_type on, so coerceValueAfterGatekeeperArgument() no longer recognises it as the type in scope (=== $input_type) and writes string into the scope. Please keep the unbound input type for that write-back, and add this snippet as a valid case. traitMethodNarrowedTemplateIsStillCheckedAfterACall calls inside the is_string branch, so it doesn't cover it.
…scope after the call Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts: # tests/Template/TraitTemplateTest.php
|
@orklah thanks, done in e1babcc: Your |
orklah
left a comment
There was a problem hiding this comment.
Thanks, the Leak snippet passes now. The write-back still uses the bound type when $input_type is rebuilt before it, though: with a single callable param, verifyType() rebuilds $input_type (getBuilder()/freeze() around line 1211) for the callable conversion, so $input_type === $bound_input_type is false and the bound type goes into the scope. Master reports nothing on this:
function takesCallable(callable $c): void { $c(); }
/** @template T of callable */
trait Leak {
/** @param T $x */
public function h($x): void {
takesCallable($x);
if ($x instanceof Closure) { echo "closure"; } // RedundantConditionGivenDocblockType
}
}
final class LeakClosure { /** @use Leak<Closure> */ use Leak; }
/** @template T */
trait Leak2 {
/** @param T $x */
public function h2($x): string {
takesCallable($x);
if (is_string($x)) { return $x; } // RedundantConditionGivenDocblockType
return "o";
}
}
final class LeakStr { /** @use Leak2<callable-string> */ use Leak2; }The HighOrderFunctionArgHandler fallback ($input_type = $original_input_type) can take the same path. Please decide with a flag rather than object identity (e.g. write back $unbound_input_type unless $replace_input_type is set), and add this snippet as a valid case.
…plate in the scope vimeo#4538 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@orklah, on your review comment from 2026-11-16 (move the binding call below the |
Psalm reports a false
ArgumentTypeCoercionwhen a trait method passes a parameter of a trait template to a method of the class using the trait with@usebinding that template.Before
After
Fixes #4538