Skip to content

fix(templates): trait method params use the types given to @use - #13429

Merged
orklah merged 13 commits into
vimeo:masterfrom
jirkace:fix/4538-trait-method-param-templates
Nov 23, 2026
Merged

orklah merged 13 commits into
vimeo:masterfrom
jirkace:fix/4538-trait-method-param-templates

Conversation

@jirkace

@jirkace jirkace commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Psalm reports a false ArgumentTypeCoercion when a trait method passes a parameter of a trait template to a method of the class using the trait with @use binding that template.

Before

<?php
/** @template T of object */
trait Foo {
    /**
     * @param T $data
     * @return T
     */
    function a($data) {
        return $this->b($data); // ArgumentTypeCoercion: Argument 1 of Bar::b expects DateTime, but parent type T:Foo as object provided
    }
}

class Bar {
    /** @use Foo<DateTime> */
    use Foo;

    function b(DateTime $data): DateTime {
        return $data;
    }
}

After

        return $this->b($data); // no issue

Fixes #4538

…#4538

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@jirkace

jirkace commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Behaviour change

  • The body of a trait method is analysed as a method of each class using the trait. The types of its parameters now have the trait's templates replaced by what @use gives (@use Foo<DateTime>: T is DateTime), as the return type already was. $this->b($data) with b(DateTime $data) no longer reports ArgumentTypeCoercion; with b(stdClass $data) it now reports InvalidArgument (master reported the coercion issue for both).
  • Only methods declared in a trait with templates, analysed in a different class, are affected; a trait used by two classes with different @use arguments is bound separately in each (new valid case).
  • The three new cases fail on master and pass on the branch. All other TraitTemplateTest cases pass; self-analysis is clean; phpcs rc 0.
  • Not run: whole test files or suites (left to CI).

@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

✅ Performance: unchanged · Types: decreased

Project Memory (MB) Wall (s) Issues Weighted (types) Taint Dead code
✅ laravel 1 751 94.4 $\color{gray}{\textsf{+0.8\%}}$ 25 906 $\color{red}{\textsf{+6}}$ $\color{green}{\textsf{-8}}$ 53 450 $\color{green}{\textsf{-12}}$ 682 0
✅ symfony 3 600 266.7 $\color{gray}{\textsf{+0.8\%}}$ 50 619 98 465 1 528 0
✅ doctrine-orm 381 20.7 $\color{gray}{\textsf{+0.6\%}}$ 3 481 6 143 0 0
✅ psl 617 25.7 $\color{gray}{\textsf{+0.1\%}}$ 1 375 5 615 1 0
✅ phpunit 455 14.6 $\color{gray}{\textsf{+1.8\%}}$ 1 731 3 410 18 0
✅ php-parser 226 9.4 $\color{gray}{\textsf{-0.1\%}}$ 17 132 21 025 0 0
✅ tempest 895 27.1 $\color{gray}{\textsf{+1.0\%}}$ 5 049 $\color{red}{\textsf{+10}}$ $\color{green}{\textsf{-10}}$ 10 534 252 0
✅ amphp-amp 68 1.8 $\color{gray}{\textsf{+1.7\%}}$ 29 49 0 0
✅ webmozarts-assert 272 $\color{gray}{\textsf{+0.1\%}}$ 4.4 $\color{gray}{\textsf{+4.3\%}}$ 577 2 720 0 0
✅ guzzle-promises 44 1.4 155 434 2 0
✅ monolog 135 5.4 $\color{gray}{\textsf{-1.5\%}}$ 913 2 479 10 0
✅ drupal 4 841 238.9 $\color{gray}{\textsf{+1.4\%}}$ 97 592 169 300 583 0
✅ wordpress 2 041 282.3 $\color{gray}{\textsf{+1.4\%}}$ 142 705 676 682 461 1
Total 15 326 992.7 $\color{gray}{\textsf{+1.1\%}}$ 347 264 $\color{red}{\textsf{+16}}$ $\color{green}{\textsf{-18}}$ 1 050 306 $\color{green}{\textsf{-12}}$ 3 537 1
How to read this table
  • Memory: Psalm's own peak figure, threads=1. More than +5 % fails, unless the PR changes composer.json.
  • Wall: base and head run on the same runner; ±10 % is noise. Above +10 % warns, never fails. re-run: a reversed second run was taken and the faster kept.
  • Issues: head count over all categories, then $\color{red}{\textsf{+added}}$ $\color{green}{\textsf{-removed}}$ against base.
  • Weighted (types): type issues weighted by error level (levels 1–8 as is, always-errors 10, strictness checks 1). Taint and dead-code issues are not weighed. The projects' own code is pinned and their dependencies resolve identically for base and head, so a change means Psalm reports more, fewer or differently serious issues. A rise is not necessarily a regression.
  • Taint: head count of Tainted* issues, then $\color{orange}{\textsf{+added}}$ $\color{orange}{\textsf{-removed}}$ against base. Both are orange as either direction needs review: more can be new detection or false positives, fewer can be fixed false positives or lost detection.
  • Dead code: head count of unused-code issues, shown only when a run reported some (findUnusedCode). More is red, fewer is green.
  • Total: sum over the projects compared on both sides. Its wall time warns above +5 % (±5 % is noise); the other thresholds apply per project.
  • Colors: $\color{red}{\textsf{red}}$ past a fail or warn threshold (or more issues), $\color{green}{\textsf{green}}$ an improvement past noise (or fewer issues), $\color{orange}{\textsf{orange}}$ needs review, $\color{gray}{\textsf{gray}}$ noise.
  • Performance: regressed if a head run crashed or timed out or a memory or wall delta is red, else improved if one is green, else unchanged. Its icon is the check result: ❌ fail · ⚠️ warn · ✅ pass; the icon next to each project is that project's result, 💥 = not comparable: base crashed or timed out (counts as ⚠️).
  • Types (heading): direction of the total weighted change, increased · decreased · unchanged. Taint and Dead code (heading): added and removed counts, present only when non-zero. Informational, never fails the check.
✅ laravel: issues +6 −8

Memory 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

Issue type added removed
InvalidArgument 0 2
MixedArgumentTypeCoercion 4 4
PossiblyInvalidArgument 2 2

Changed in place (3); {self} is the class named after the file

@​@​ 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 provided

Removed (2)

  • src/Illuminate/Database/Concerns/BuildsQueries.php:208 InvalidArgument (error): Argument 1 expects Collection<int, TValue:BuildsQueries as mixed>, but Collection<int, stdClass> provided
  • src/Illuminate/Database/Concerns/BuildsQueries.php:70 InvalidArgument (error): Argument 1 expects Collection<int, TValue:BuildsQueries as mixed>, but Collection<int, stdClass> provided
✅ tempest: issues +10 −10

Memory 895 → 895 MB (+0.0 %) · Wall 26.8 → 27.1 s (+1.0 %)

Issue type added removed
PossiblyInvalidArgument 10 10

Changed in place (5); {self} is the class named after the file

@​@​ 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>) provided

head 0bbfecf · base 96953a3 (merge-base) · workflow run

jirkace and others added 2 commits November 11, 2026 09:05
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
# Conflicts:
#	tests/Template/TraitTemplateTest.php
@jirkace

jirkace commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

Checked against current master (683c22595) by running this PR's cases singly: traitMethodParamIsTheTypeGivenToUse, traitUsedWithDifferentTypesBindsEachOfThem and traitMethodParamIsNotAcceptedWhereTheUseTypeDoesNotFit all fail on master, so the PR changes the behaviour the cases describe.

Not changed, read only: finding 1 (the perf run's nine new reports on laravel BuildsQueries.php, Argument 1 expects TModel:Bu…, look like false positives from rebinding the parameter types of a trait method; I cannot reproduce that without the Laravel sources, so this needs the author's look at those lines before it lands) and finding 2 (only parameter types are rebound, not @var/@param-out/@psalm-assert types written with the trait's templates).

Ran: the three cases of the PR on master. No code change pushed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

jirkace and others added 2 commits November 16, 2026 21:04
…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>
@jirkace

jirkace commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the review (809095698e, on top of current master):

  • bindTraitTemplatesToUse() now runs after the $param_type->check(...) block, just before addParentNodes(), so the covariance check sees the trait's own templates again.
  • New invalid cases covariantTraitTemplateInAParameterIsStillReportedWithAConcreteUse (@use EV<int>) and covariantClassTemplateInAParameterIsStillReportedWhereTheTraitIsUsedWithIt (class @template-covariant TValue, @use EV<TValue>), both expecting InvalidTemplateParam; both fail on the previous head and pass now. The three earlier cases still pass singly.
  • traitMethodParamIsNotAcceptedWhereTheUseTypeDoesNotFit pins the message (Argument 1 of Bar::b expects stdClass, but DateTime provided).

Run: the five cases above singly, phpcs, one full self-analysis (clean). Not run: the rest of TraitTemplateTest (CI) and the perf report.

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, so r(&$d) reports ReferenceConstraintViolation even with an empty body. The by-ref constraint, and @param-out, need the same binding.
  • Narrowing in the body: is_string($x) now reports RedundantConditionGivenDocblockType for one user and DocblockTypeContradiction + NoValue for 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 @use type 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>
@jirkace

jirkace commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 1a0f814.

The parameter types are no longer bound: they keep the trait's own templates, which fixes both false positives from the review (is_string($x) on a template, and ReferenceConstraintViolation for a by-ref T parameter). What fixes #4538 is the binding of the type of an argument given to a call inside a trait method (ArgumentAnalyzer::verifyType() through the now public FunctionLikeAnalyzer::bindTraitTemplatesToUse()).

  • Added both snippets as valid cases (traitMethodMayBranchOnItsTemplateWhateverTheUseTypeIs, traitMethodMayTakeItsTemplateByReference) and traitTemplateIsBoundInAListParamAndInANestedTrait. The three existing valid cases and the covariance/message cases pass as before.
  • Limitation: only a call inside a trait method itself is covered, not inside a closure in it (the closure's storage is not the method's).

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 BuildsQueries<\stdClass> deltas are not re-checked.

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) reports RedundantCondition.
  • 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 trait Manip<TKey, TValue> with /** @param callable(TInit|TRet, TValue, TKey): TRet $callback */ reduce() calling red($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>
@jirkace

jirkace commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Pushed c4c3973 for the review of 1a0f814. Probed first on the previous head and on master (errorLevel 1):

  • Narrowing: confirmed. Your Red snippet reported InvalidScalarArgument for takesString($x) under @use Red<int> (and takesInt under Red<string>), master reports nothing. After is_string($x) the argument is T:Red as string; binding replaced the whole atomic by int and dropped the narrowing. A template whose as differs from the declared bound is now left as it is, only the others are bound. New traitMethodNarrowsItsTemplateWhateverTheUseTypeIs (fails on the previous head) and the guard traitMethodNarrowedTemplateIsStillCheckedAfterACall.
  • Bound type flowing back (RedundantCondition after takesString($x) under @use Leak<string>): not reproduced on the previous head (no issue reported); the guard case above covers that shape (is_string after the call is not reported as redundant).
  • reduce shape: confirmed. The called function's callable(TInit|TRet, TValue, TKey) parameter was inferred from the unbound $this->value (TValue:Manip) while the callback argument was bound (TValue:Arr), so red($this->value, $callback, $initial) reported InvalidArgument. The parameter type is now bound like the argument in ArgumentAnalyzer::verifyType. New traitMethodPassesItsTemplatedArrayAndCallbackToATemplatedFunction (fails on the previous head with exactly that message).
  • Blank line before addParentNodes() removed.

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).

@jirkace

jirkace commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Local benchmark run for the triage report's perf findings (the benchmark runner itself is not available to me): Psalm on src/Illuminate of laravel/framework (shallow clone of its default branch, errorLevel 1, PHP 8.3, ensureArrayStringOffsetsExist, no baseline, --no-cache), this branch merged with current master vs master itself, issues compared as sorted lines.

  • fix(templates): trait method params use the types given to @use #13429: +4 / -5, but 4 of each are the same 4 MixedArgumentTypeCoercion of EnumeratesValues.php (309 and 547, for Collection and LazyCollection) with the template of the using class in the message (TValue:Illuminate\Support\Collection instead of TValue:...\Traits\EnumeratesValues); one real removal, the InvalidArgument at Database/Concerns/BuildsQueries.php:70 (Collection<int, stdClass> for BuildsQueries<stdClass>).

Limits: tempest, which the review cites, is not covered. Not run: the full suite (CI).

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

jirkace and others added 4 commits November 20, 2026 22:27
…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
@jirkace

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

@orklah thanks, done in e1babcc: ArgumentAnalyzer keeps the unbound input type for the write-back of coerceValueAfterGatekeeperArgument(), so the type bound to the template for the call doesn't flow back into the body.

Your Leak snippet is the new valid case TraitTemplateTest::traitMethodArgumentKeepsItsTemplateTypeAfterTheCall, and traitMethodArgumentOfATemplateUsedAsMixedKeepsItsTemplateTypeAfterTheCall covers the same order (call, then check) with a template used as mixed. Both report RedundantCondition: Type string for $x is always string on the commit before the fix and pass on the current head (master merged in). CI is green apart from label. PHPUnit suite not run locally.

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@jirkace

jirkace commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@orklah, on your review comment from 2026-11-16 (move the binding call below the $param_type->check(...) block in FunctionLikeAnalyzer): that call site is gone. Since c4c3973 the parameter types of a trait method keep the trait's own templates when the method is analysed, so check() sees them as written. The binding is applied in ArgumentAnalyzer (lines 1070 and 1076 of the current head) to the argument and parameter types of a call made inside the trait method, through the public FunctionLikeAnalyzer::bindTraitTemplatesToUse(). GitHub marks the thread as outdated. I did not resolve it.

@orklah orklah added the release:fix The PR will be included in 'Fixes' section of the release notes label Nov 23, 2026

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @jirkace!

@orklah
orklah merged commit cad5c51 into vimeo:master Nov 23, 2026
72 of 73 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release:fix The PR will be included in 'Fixes' section of the release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

False positive ArgumentTypeCoercion in templated trait

2 participants